auto-i18n-scripts
v1.0.5
Published
auto handle internationalization
Downloads
15
Maintainers
Readme
使用方式
1.1 安装脚本
npm install auto-i18n-scripts -D 或者 yarn add auto-i18n-scripts -D
如果没有安装 vue-i18n,也需安装 vue-i18n。
1.2 配置 loader
使用运行国际化脚本的项目启动时还需要去项目配置文件中配置 loader。 webpack 工程 对于使用 vue-cli 创建的工程配置文件为 vue.config.js,需要在 chainWebpack 配置加入以下 loader 以及检查是否配置 src 目录的别名。
chainWebpack: config => {
config.module
.rule('vue')
.use('auto-i18n-scripts/webpack-plugin')
.loader('auto-i18n-scripts/webpack-plugin')
.options({
localeFile: path.join(process.cwd(), 'locale/zh.js')
})
.end()
config.module
.rule()
.test(/\.(jsx|js|ts|tsx)?$/)
.include.add(resolve('src'))
.end()
.use('babel-loader')
.loader('babel-loader')
.end()
config.module
.rule()
.test(/\.(jsx|js|ts|tsx)?$/)
.include.add(resolve('src'))
.end()
.use('auto-i18n-scripts/webpack-plugin')
.loader('auto-i18n-scripts/webpack-plugin')
.options({
localeFile: path.join(process.cwd(), 'locale/zh.js')
})
.end()
},
configureWebpack: () => {
const options = {
resolve: {
alias: {
'@': resolve('src'), // 配置src别名为@
}
}
}
}
vite 工程
vite.config.js 需要配置加入以下 loader 以及安装@originjs/vite-plugin-commonjs
和@rollup/plugin-commonjs
依赖用于解析使用 cjs 的文件以及检查是否配置 src 目录的别名。
yarn add @originjs/vite-plugin-commonjs @rollup/plugin-commonjs -D
或
npm install @originjs/vite-plugin-commonjs @rollup/plugin-commonjs -D
import { viteCommonjs } from '@originjs/vite-plugin-commonjs'
const i18nPlugin = require('auto-i18n-scripts/vite-plugin')
import commonjs from '@rollup/plugin-commonjs'
export default defineConfig({
plugins: [i18nPlugin(), viteCommonjs(), commonjs()],
resolve: {
alias: {
'@': resolve(__dirname, 'src') // 配置src别名为@
}
}
})
注意!若是在 uni 项目中时 plugins 配置时需要在 uni()配置后即
plugins: [uni(), i18nPlugin(), viteCommonjs(), commonjs()]
1.3 运行脚本
终端输入命令 npx i18n 后会出现多个操作选项: ? 想要做什么? (Use arrow keys)
全部运行 初始化配置文件 还原国际化:针对使用 i18n 做过国际化的项目,格式为$t('xxx')或 i18n('xxxx') 遍历获取 src 下中文资源并根据语言译本翻译成目标语言
1.3.1 全部运行脚本
选择全部运行时,会运行整个国际化脚本,包括初始化配置文件、抓取国际化资源、生成目标语言包等操作 运行脚本时会有多个配置选项: ? 设置国际化文件的存放目录,默认为根目录下的 locale 目录,请务必设置一个单独的目录来放置国际化资源文件(locale) ? 设置中文文本的文件名,默认为 zh,会自动添加.js 后缀(zh) ? 设置目标语言名称,默认为 en (en) 第一个配置项是设置国际化目录,会自动生成相对应的目录文件夹,译本资源 origin 和中文资源以及目标翻译语言都会生成在这个目录下。默认为根目录的 locale 文件夹 第二个配置项是抓取国际化资源后生成文件名,注意不需要加后缀!默认为 zh 第三个配置项为需要翻译的目标语言名,建议使用语言 code。后续会使用此变量生成目录以及后续一些配置项变量使用
1.3.2 初始化配置文件
运行此脚本只会初始化国际化配置文件 src/i18n.js 文件,以及会根据 vue-i18n 插件的版本生成不同的配置文件 该脚本的配置选项与全部运行脚本时一致
1.3.3 还原国际化
此脚本功能为把已做过国际化的项目还原。即把国际化标签还原成中文: 格式为$t('xxx')或 i18n('xxxx') 还原成相应中文。
? 还原国际化中文资源路径 src/lib/i18n/lang/ ? 还原国际化中文资源文件名 (zh-cn) 第一个配置项为该项目的国际化资源文件目录,注意是目录不需要到文件名。默认为 src/lib/i18n/lang/ 第二个配置项为国际化中文资源文件名。该文件为项目国际化中文资源包。 注意!中文资源包需要为 cjs 的导出格式即:module.exports = {}方式,若为 esm 方式需要手动改动一下。不然脚本会抛出错误。 1.3.4 遍历获取 src 下中文资源并根据语言译本翻译成目标语言 该脚本为抓取 src 目录下的所有中文资源,并自动和译本对比后生成目标语言 配置项与全部运行脚本一致。 此脚本可以在项目已经使用过国际化脚本后续有新增的中文资源时使用,不需要再去跑全部运行脚本