项目根目录,创建一个文件util.js,内容如下:
const path = './src' // 文件夹地址
const outerFileName = './src/locales/zh-CN.ts' // 输出文件
const outFile=['.umi', 'locales', 'utils']// 需要排除的文件夹
const fs = require('fs')
try {
const filePathArr = []
// 递归获取所有文件路径(ts、tsx)
function getAllFilesPath(path) {
const files = fs.readdirSync(path).filter(file => !outFile.includes(file));
files.forEach((file) => {
const filePath = `${path}/${file}`;
if (/\.tsx?$/.test(file)) { // 检查文件是否以 .ts 或 .tsx 结尾
if (!/\/locales\//.test(filePath)) { // 检查文件路径是否包含 locales 目录
filePathArr.push(filePath);
}
} else if (fs.statSync(filePath).isDirectory()) {
getAllFilesPath(filePath); // 递归处理子目录
}
});
}
getAllFilesPath(path)
// 遍历所有的文件,提取其中的中文字符串
const chineseWords = [];
filePathArr.forEach((filePath) => {
const fileContent = fs.readFileSync(filePath, 'utf8');
const contentWithoutComments = removeComments(fileContent);
const matches = contentWithoutComments.match(/[\u4e00-\u9fa5\s]+/g); // 匹配中文字符和空格
if (matches) {
matches.forEach((match) => {
const trimmedMatch = match.trim(); // 去除首尾空格
if (trimmedMatch !== '' && !chineseWords.includes(trimmedMatch)) {
chineseWords.push(trimmedMatch);
}
});
}
});
// 将中文字符串按照 locales 文件的格式输出到 ts 文件
// 将中文字符串写入 ts 文件
let outputString = 'export default {\n';
chineseWords.forEach((word) => {
outputString += ` "${word}": "${word}",\n`;
});
outputString += '};\n';
// 将中文字符串写入 ts 文件
fs.writeFileSync(outerFileName, outputString);
console.debug('输出 JSON 文件成功:', outerFileName);
// 去除注释函数
function removeComments(content) {
return content.replace(/(\/\*[\s\S]*?\*\/)|(\/\/.*$)/gm, '');
}
} catch (err) {
console.debug(err)
}
最后再执行node -util.js命令就可以看到指定文件夹目录下生成的数据了