Skip to content

aaimio/swc-plugin-static-i18n

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

swc-plugin-static-i18n

A Speedy Web Compiler (SWC) plugin that replaces (translatable) strings at build time.

Getting started

⚠️ This is still in development and below instructions do not work.

  1. Install the plugin:
pnpm i swc-plugin-static-i18n
  1. 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 }}",
};
  1. Add configuration to .swcrc.mjs or next.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>
  )
}

Wishlist

  • 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 to react-i18next) for interpolation

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Languages