a babel
plugin for automating internationalization
- 🚀 Automatic translation from one language to another language
- 💼 Automated namespace management
- 🤝 Compatible with your existing i18n implementation
- 🛴 Say goodbye to manually scripting
i18next-scanner
- 🍻 Support Google and Youdao translation API
- Project must use i18next as the internationalization framework
pnpm install babel-plugin-i18next -D
- fork this repository
pnpm i
pnpm build
cd packages/demo
pnpm serve
- localhost:8080
- in babel config file
babel.config.js
module.exports = {
presets: [...],
plugins: [
[
"i18next",
{
localePath: path.resolve(__dirname, "src", "locales"),
languages: [
{ code: "en" },
{ code: "zh" },
],
primaryLng: "en",
defaultNS: "default",
include: [`${path.resolve(__dirname, 'src')}/**/*.{js,jsx,ts,tsx,vue}`],
translateApi: { type: 'google', secretFile: path.resolve(__dirname, '.translaterc') },
interpolation: {
prefix: '{{',
suffix: '}}',
},
},
],
...
],
};
- Add one extra function in your i18n module and export it
// i18n.ts
import i18next from 'i18next';
export default {
...i18next,
s: (text: string, ns?: { [key: string]: any } | string, opts?: { [key: string]: any }) => text,
};
- In your source code, wrap the text which needs to be translated with
i18n.s
ori18next.s
// souce code
import i18n from 'i18n';
// import i18next from 'i18n'; // i18next is also ok
...
// after compile it will be
// const title = i18n.t('myNs:title');
const title = i18n.s('title', 'myNs');
- if in
development
mode, will translate the text which not found in locale source, or untranslated. Meanwhile will transformi18n.s
–>i18n.t
- If in
production
mode, will transformi18n.s
–>i18n.t
, if find untranslated text, will throw error and exit built.
-
localePath
string | string[]
- (required)The absolute path of the multilingual locale source folder, please make sure that there are source files names aslngCode.json
in the path -
Languages
{ code: string }[]
- (required)language with its code -
primaryLng
string
- (required)primary language -
include
string | string[]
- (required)the source files should be scaned for i18n, should beglob
-
defaultNs
string
- (required) default namespace -
translateApi
{ type: 'google' | 'youdao', secretFile: string }
- When this option is not configured, the plugin will call the free Google Translate library @vitalets/google-translate-api for translation, However, in this case, the stability of translation cannot be guaranteed, and errors such as 403/429 may occur after calling multiple translations on the same gateway, indicating that it is restricted by Google. It is recommended that users apply for a Google Cloud account. The monthly free traffic of 500,000 characters can basically guarantee the use of a medium-to-large front-end application. After completing the application, create an API credential, that is, an API key. After configuration, stable translation can be performed. Meanwhile Youdao is also an option for it