78 lines
2.0 KiB
JavaScript
78 lines
2.0 KiB
JavaScript
const fs = require("fs");
|
|
const path = require("path");
|
|
const glob = require("glob");
|
|
|
|
// 读取中文语言包
|
|
const zhCN = require("../i8n.js");
|
|
|
|
// 递归获取所有需要处理的文件
|
|
function getAllFiles(dir, patterns) {
|
|
return new Promise((resolve, reject) => {
|
|
glob(
|
|
patterns.join("|"),
|
|
{
|
|
cwd: dir,
|
|
ignore: ["node_modules/**", "dist/**", "**/i18n/**", "**/languages/**"],
|
|
},
|
|
(err, files) => {
|
|
if (err) reject(err);
|
|
resolve(files);
|
|
}
|
|
);
|
|
});
|
|
}
|
|
|
|
// 获取嵌套对象的值
|
|
function getNestedValue(obj, path) {
|
|
return path.split(".").reduce((current, key) => current && current[key], obj);
|
|
}
|
|
|
|
// 替换文件内容
|
|
function replaceContent(content) {
|
|
// 替换模板中的 $t('key')
|
|
content = content.replace(/\$t\(['"]([^'"]+)['"]\)/g, (match, key) => {
|
|
const value = getNestedValue(zhCN, key);
|
|
return value ? `"${value}"` : match;
|
|
});
|
|
|
|
// 替换 JavaScript 中的 this.$t('key')
|
|
content = content.replace(/this\.\$t\(['"]([^'"]+)['"]\)/g, (match, key) => {
|
|
const value = getNestedValue(zhCN, key);
|
|
return value ? `"${value}"` : match;
|
|
});
|
|
|
|
return content;
|
|
}
|
|
|
|
// 主函数
|
|
async function main() {
|
|
try {
|
|
// 只处理 views 和 components 目录
|
|
const patterns = ["views/**/*.{vue,js,ts}", "components/**/*.{vue,js,ts}"];
|
|
const files = await getAllFiles(
|
|
path.resolve(__dirname, "../src"),
|
|
patterns
|
|
);
|
|
|
|
for (const file of files) {
|
|
const filePath = path.resolve(__dirname, "../src", file);
|
|
let content = fs.readFileSync(filePath, "utf8");
|
|
|
|
// 替换内容
|
|
const newContent = replaceContent(content);
|
|
|
|
// 如果内容有变化,则写入文件
|
|
if (newContent !== content) {
|
|
fs.writeFileSync(filePath, newContent, "utf8");
|
|
console.log(`已处理文件: ${file}`);
|
|
}
|
|
}
|
|
|
|
console.log("所有文件处理完成!");
|
|
} catch (error) {
|
|
console.error("处理过程中出错:", error);
|
|
}
|
|
}
|
|
|
|
main();
|