89 lines
2.3 KiB
JavaScript
89 lines
2.3 KiB
JavaScript
const fs = require("fs");
|
|
const path = require("path");
|
|
const { glob } = require("glob");
|
|
|
|
// 读取中文语言包
|
|
const zhCN = require("../i8n.js");
|
|
|
|
// 递归获取所有需要处理的文件
|
|
async function getAllFiles(dir, patterns) {
|
|
console.log("搜索目录:", dir);
|
|
console.log("搜索模式:", patterns);
|
|
const files = await glob(patterns, {
|
|
cwd: dir,
|
|
ignore: ["node_modules/**", "dist/**", "**/i18n/**", "**/languages/**"],
|
|
});
|
|
console.log("找到的文件数量:", files.length);
|
|
return files;
|
|
}
|
|
|
|
// 获取嵌套对象的值
|
|
function getNestedValue(obj, path) {
|
|
return path.split(".").reduce((current, key) => current && current[key], obj);
|
|
}
|
|
|
|
// 替换文件内容
|
|
function replaceContent(content) {
|
|
// 替换模板中的 $t('key')
|
|
content = content.replace(
|
|
/(?<!this\.|that\.)\$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 {
|
|
const srcPath = path.resolve(__dirname, "../");
|
|
console.log(srcPath);
|
|
console.log("源文件目录:", srcPath);
|
|
|
|
// 只处理 views 和 components 目录
|
|
const patterns = [
|
|
"pages/**/*.vue",
|
|
"pages/**/*.js",
|
|
"pages/**/*.ts",
|
|
"components/**/*.vue",
|
|
"components/**/*.js",
|
|
"components/**/*.ts",
|
|
];
|
|
|
|
const files = await getAllFiles(srcPath, patterns);
|
|
|
|
if (files.length === 0) {
|
|
console.log("警告:没有找到匹配的文件!");
|
|
return;
|
|
}
|
|
|
|
for (const file of files) {
|
|
const filePath = path.resolve(srcPath, file);
|
|
console.log("处理文件:", filePath);
|
|
|
|
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();
|