A Speedy Web Compiler (SWC) plugin that replaces (translatable) strings at build time.
⚠️ This is still in development and below instructions do not work.
- Install the plugin:
pnpm i swc-plugin-static-i18n
- Define your translatable strings:
export const en_GB = {
"Hello World": "Hello World",
"Goodbye {{ name }}": "Goodbye {{ name }}",
};
/** @type {{ [key in keyof en_GB]: string }} */
export const nl_NL = {
"Hello World": "Hallo Wereld",
"Goodbye {{ name }}": "Tot ziens {{ name }}",
};
- Add configuration to
.swcrc.mjs
ornext.config.js
:
import { nl_NL, en_GB } from "./strings";
export default {
jsc: {
plugins: [
[
"swc-plugin-static-i18n",
{
function_name: "translate",
strings: (() => {
switch (process.env.LOCALE) {
case "nl_NL": {
return nl_NL;
}
default: {
return en_GB;
}
}
})(),
},
],
],
},
};
In this example, the plugin will replace all translate
calls with the
replacement strings in the specified strings
parameter, i.e.:
const SomeComponent = () => {
return (
<div className='p-2'>
- <h1>{translate("Hello World")}</h1>
+ <h1>{translate("Hallo Wereld")}</h1>
</div>
)
}
-
Add a config option to inline strings if the
translate
function doesn't do anything (other than acting as a point to inject strings)- For example:
const SomeComponent = () => { return ( <div className='p-2'> - <h1>{translate("Hello World")}</h1> + <h1>{"Hallo Wereld"}</h1> </div> ) }
-
Expose a
translate
function and<Trans>
component (similar toreact-i18next
) for interpolation