babel-plugin-auto-i18n
v1.0.0
Published
Babel plugin for auto i18n transformation - Chinese → $t(key)
Downloads
2
Maintainers
Readme
babel-plugin-auto-i18n
Babel 编译时自动国际化插件 - 适用于 Webpack 等构建工具
核心功能:在编译时自动将中文字符串转换为 t(key) 调用,实现零运行时开销的国际化。
📦 安装
npm install babel-plugin-auto-i18n -D
# 或
pnpm add babel-plugin-auto-i18n -D
# 或
yarn add babel-plugin-auto-i18n -D配合运行时使用:
# Vue 项目
npm install @mico_fe/i18n-vue
# React 项目
npm install @mico_fe/i18n-react🎯 工作原理
源代码 编译后
┌─────────────────────┐ ┌─────────────────────────┐
│ const msg = '你好' │ → │ const msg = t('xxx') │
│ <p>欢迎使用</p> │ → │ <p>{t('yyy')}</p> │
│ alert('操作成功') │ → │ alert(t('zzz')) │
└─────────────────────┘ └─────────────────────────┘🚀 配置
Webpack + Vue
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
'@babel/preset-typescript',
],
plugins: [
['babel-plugin-auto-i18n', {
localesDir: './src/locales',
sourceLocale: 'zh-CN',
translateFn: 't',
debug: false,
}],
'@vue/babel-plugin-jsx', // 如果使用 JSX
],
},
},
],
},
],
},
}Webpack + React
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(ts|tsx|js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
['@babel/preset-react', { runtime: 'automatic' }],
'@babel/preset-typescript',
],
plugins: [
['babel-plugin-auto-i18n', {
localesDir: './src/locales',
sourceLocale: 'zh-CN',
translateFn: 't',
debug: false,
}],
],
},
},
},
],
},
}Babel 配置文件
也可以在 .babelrc 或 babel.config.js 中配置:
// babel.config.js
module.exports = {
presets: [
'@babel/preset-env',
'@babel/preset-typescript',
],
plugins: [
['babel-plugin-auto-i18n', {
localesDir: './src/locales',
sourceLocale: 'zh-CN',
translateFn: 't',
}],
],
}📖 配置选项
| 选项 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| localesDir | string | './src/locales' | 语言包目录(相对于项目根目录) |
| sourceLocale | string | 'zh-CN' | 源语言代码 |
| translateFn | string | 't' | 转换后的函数名 |
| excludeConsole | boolean | true | 排除 console.* 中的中文 |
| debug | boolean | false | 调试模式,打印转换日志 |
| onMissing | 'warn' \| 'error' \| 'ignore' | 'warn' | 缺少翻译的处理方式 |
🔧 转换规则
1. 字符串字面量
// 转换前
const message = '操作成功'
const title = '确认删除?'
// 转换后
const message = t('message.success')
const title = t('dialog.confirmDelete')2. 模板字符串(纯静态)
// 转换前
const msg = `欢迎使用`
// 转换后
const msg = t('message.welcome')
// ⚠️ 包含变量的模板字符串不会转换
const greeting = `你好,${name}` // 不转换3. JSX 文本
// 转换前
<p>你好世界</p>
<button>提交</button>
// 转换后
<p>{t('message.hello')}</p>
<button>{t('button.submit')}</button>4. JSX 属性
// 转换前
<input placeholder="请输入用户名" />
<button title="点击提交">提交</button>
// 转换后
<input placeholder={t('form.enterUsername')} />
<button title={t('button.clickSubmit')}>{t('button.submit')}</button>5. 不转换的情况
// 1. console.* 中的中文(excludeConsole: true)
console.log('调试信息') // 不转换
console.error('错误信息') // 不转换
// 2. 已经在翻译函数中的字符串
t('button.submit') // 不转换
tt('欢迎使用') // 不转换
$t('message.hello') // 不转换
// 3. 注释中的中文
// 这是中文注释 // 不转换
// 4. 对象键名
const obj = { '中文键': value } // 键名不转换,值会转换📁 语言包格式
插件会自动读取 localesDir 目录下的 {sourceLocale}.json 文件:
src/locales/
├── zh-CN.json # 必须存在!
├── en-US.json
└── index.tszh-CN.json(源语言必须有中文)
{
"message.success": "操作成功",
"message.hello": "你好世界",
"button.submit": "提交",
"form.enterUsername": "请输入用户名"
}⚠️ 重要:排除 node_modules
必须在 loader 配置中排除 node_modules,否则会错误转换依赖包:
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/, // 重要!
use: 'babel-loader',
}🔌 与运行时配合
Vue
// main.ts
import { createApp } from 'vue'
import { setupLangs } from '@mico_fe/i18n-vue'
import * as localeModule from './locales'
import App from './App.vue'
const app = createApp(App)
setupLangs(app, {
localeModule,
fallbackLang: 'zh-CN',
}).then(() => {
app.mount('#app')
})React
// main.tsx
import { createRoot } from 'react-dom/client'
import { I18nProvider } from '@mico_fe/i18n-react'
import localeModule from './locales'
import App from './App'
createRoot(document.getElementById('root')!).render(
<I18nProvider localeModule={localeModule}>
<App />
</I18nProvider>
)🐛 调试
开启 debug 模式查看转换详情:
['babel-plugin-auto-i18n', {
debug: true,
}]输出示例:
[babel-plugin-auto-i18n] Loaded 50 mappings
[babel-plugin-auto-i18n] Processing: /src/App.tsx
[babel-plugin-auto-i18n] Transformed 3 strings:
- 你好世界 → t('message.hello')
- 提交 → t('button.submit')
- 操作成功 → t('message.success')
[babel-plugin-auto-i18n] Missing translations:
- 未找到的文案❓ 常见问题
Q: 为什么转换后报 "t is not defined"?
A: 确保:
- 已安装运行时 (
@mico_fe/i18n-vue或@mico_fe/i18n-react) - 正确初始化了 i18n
- Webpack 配置中正确排除了
node_modules
Q: 为什么某些中文没有被转换?
A: 可能原因:
- 语言包中没有对应的中文文案
- 中文在 console.log 中(默认排除)
- 中文在注释中
- 字符串已经在翻译函数调用中
Q: 如何处理动态字符串?
A: 使用运行时的 tt() 函数:
// 动态获取的文案
const text = await api.getMessage()
const translated = tt(text) // 运行时翻译📄 License
MIT
