以locals文件夹下面存放国际化文件为例,我们将zh存放中文为例,下面将演示遍历所有中文文件,并进行翻译,翻译后生成到对应的文件夹下,保持和中文目录下的一致的目录结构。
目录结构如下
├── index.js
├── translate-core
│ ├── google-translate.js
│ ├── index.js
│ └── string.js
└── translate-helper.js
需要的npm包如下
"jsonic": "^0.3.1",
"klaw": "^3.0.0",
"recast": "^0.19.1",
"request": "^2.88.2",
"request-promise-native": "^1.0.8",
"rimraf": "^3.0.2",
"through2": "^3.0.1"
在使用Node脚本对前端国际化初探已经做了翻译API,的封装,本次将上次内容放到translate-core下。
translate-helper存放了一些工具函数,内容如下
const through2 = require("through2")
const path = require("path")
const fs = require("fs")
const filterFolder = through2.obj(function (item, enc, next) {
// 添加文件夹标识
item.isFolder = false
if (item.stats.isDirectory()) {
item.isFolder = true
}
this.push(item)
next()
})
const filterJsFile = (item) => {
// 这种方式过滤会把文件夹下的js文件过滤掉
const extname = path.extname(item)
return extname === ".js"
}
const filterJs = through2.obj(function (item, enc, next) {
// 过滤所有js文件
if (path.extname(item.path) === ".js") {
this.push(item)
}
next()
})
/**
* 读取路径信息
* @param {string} path 路径
*/
function getStat(path) {
return new Promise((resolve, reject) => {
fs.stat(path, (err, stats) => {
if (err) {
resolve(false)
} else {
resolve(stats)
}
})
})
}
/**
* 创建路径
* @param {string} dir 路径
*/
function mkdir(dir) {
return new Promise((resolve, reject) => {
fs.mkdir(dir, (err) =>