preact-i18n
Example
JavaScript
export default {
"string-id": "EN",
"string-param": (param) => `${param}, EN`
}
export default {
"string-id": "SV",
"string-param": (param) => `${param}, SV`
}
import { withLanguage, storeLocale, changeLanguage } from "@weedzcokie/i18n-preact";
storeLocale({
"en": () => [import("./en.js")],
"sv": () => [import("./sv.js")],
});
function App(props) {
return (
<div>
<input onclick={() => changeLanguage("sv")} value="Change language" />
<p>{this.props.t("string-id")}</p>
<p>{this.props.t("string-param")("Hello World!")}</p>
</div>
);
}
export default withLanguage(App);
TypeScript
tsconfig.json
:
{
"compilerOptions": {
// ...
},
"include": [
"src",
"@types"
]
}
@types/@weedzcokie/i18n-preact.d.ts
:
import { locales } from "src/i18n";
import ns1 from "src/i18n/en";
declare module "@weedzcokie/i18n-preact" {
type AllLocales = typeof locales;
type StringValues = typeof ns1;
type AllStrings = {
[K in keyof StringValues]: StringValues[K];
};
interface StringValue extends AllStrings {}
interface Locales extends AllLocales {}
}
export default {
"string-id": "EN",
"string-param": (param: string) => `${param}, EN`
}
export default {
"string-id": "SV",
"string-param": (param: string) => `${param}, SV`
} as typeof import("./en").default;
import { storeLocale } from "@weedzcokie/i18n-preact";
export const locales = {
"en": () => [import("./en")],
"sv": () => [import("./sv")],
};
storeLocale(locales);
import { changeLanguage, withLanguage } from "@weedzcokie/i18n-preact";
import "src/i18n";
function App(props: LanguageProps) {
return (
<div>
<input onclick={() => changeLanguage("sv")} value="Change language" />
<p>{this.props.t("string-id")}</p>
<p>{this.props.t("string-param")("Hello World!")}</p>
</div>
);
}
export default withLanguage(App);
preact-router
With preact-router
we can to declare "routable" components as:
import type { LanguageProps } from "@weedzcokie/i18n-preact";
import { RoutableProps } from "preact-router";
import withLanguage from "../i18n";
type Props = RoutableProps & LanguageProps & {
msg: string
};
function About(props: Props) {
return (
<div>
<h1>About</h1>
<p>{props.msg}</p>
<p>{props.t("string-id")}</p>
</div>
);
}
export default withLanguage(About);
import { Route, Router } from "preact-router";
<Router>
<About path="/about" msg="Test props" />
{ /* or as a `Route` */}
<Route component={About} path="/about" msg="Test props" />
</Router>
Hook
import { useLanguage } from "@weedzcokie/i18n-preact";
import "src/i18n";
type Props = {
msg: string
};
function About(props: Props) {
const t = useLanguage();
return (
<div>
<h1>About</h1>
<p>{props.msg}</p>
<p>{t["string-id"]}</p>
</div>
);
}