Vue2(Options API)项目静态文本提取:多语言国际化实现问询
提取Vue2模板静态文本的实用方案
一、手动标记+正则批量扫查(快速落地)
1. 规范翻译调用格式
把模板里的静态文本(含变量的短语)统一替换成全局翻译方法的调用,比如:
原模板代码:
<div>欢迎[用户名],是否要将[商品名称]加入购物车?</div>
替换后:
<div>{{ babelfishTranslate('welcome_add_cart', { username: 用户名, goodsName: 商品名称 }) }}</div>
这里welcome_add_cart是自定义翻译键,变量用对象传递,替换原文本里的[xxx]占位符。
2. 脚本扫查未标记文本
写个Node.js脚本遍历所有.vue文件,用正则匹配模板中未被翻译方法包裹的静态文本:
const fs = require('fs'); const path = require('path'); // 匹配模板内的纯文本片段(排除插值、指令和已标记的翻译内容) const textRegex = />([^<>{}\s]+(?:\s+[^<>{}\s]+)*)</g; function scanVueFiles(dir) { const files = fs.readdirSync(dir); files.forEach(file => { const fullPath = path.join(dir, file); if (fs.statSync(fullPath).isDirectory()) { scanVueFiles(fullPath); } else if (file.endsWith('.vue')) { const content = fs.readFileSync(fullPath, 'utf8'); const templateMatch = content.match(/<template>([\s\S]*?)<\/template>/); if (templateMatch) { const templateContent = templateMatch[1]; // 过滤掉已用babelfishTranslate标记的内容 const filteredContent = templateContent.replace(/babelfishTranslate\([\s\S]*?\)/g, ''); let match; while ((match = textRegex.exec(filteredContent)) !== null) { const text = match[1].trim(); if (text) { console.log(`文件: ${fullPath} | 待标记文本: "${text}"`); // 可将结果写入JSON文件,后续统一处理 } } } } }); } // 执行扫描,传入项目src目录路径 scanVueFiles('./src');
注意:正则需要根据项目实际情况调整,比如处理带换行、特殊字符的文本。
二、AST解析(精准提取,适合复杂项目)
用vue-template-compiler解析Vue模板的抽象语法树(AST),精准遍历文本节点提取内容:
const fs = require('fs'); const path = require('path'); const compiler = require('vue-template-compiler'); function extractTextNodes(node, texts = []) { if (node.type === 2) { // 识别文本节点 const text = node.text.trim(); // 排除空文本和已标记的翻译内容 if (text && !text.includes('babelfishTranslate')) { texts.push(text); } } // 递归遍历子节点 if (node.children) { node.children.forEach(child => extractTextNodes(child, texts)); } return texts; } function scanVueFiles(dir) { const files = fs.readdirSync(dir); files.forEach(file => { const fullPath = path.join(dir, file); if (fs.statSync(fullPath).isDirectory()) { scanVueFiles(fullPath); } else if (file.endsWith('.vue')) { const content = fs.readFileSync(fullPath, 'utf8'); const templateMatch = content.match(/<template>([\s\S]*?)<\/template>/); if (templateMatch) { const { ast } = compiler.compile(templateMatch[1]); const texts = extractTextNodes(ast); texts.forEach(text => { console.log(`文件: ${fullPath} | 待标记文本: "${text}"`); }); } } }); } scanVueFiles('./src');
这种方法不会误匹配模板里的代码、插值表达式或指令,准确率更高,适合大型项目。
三、带变量文本的后续处理
提取到带[xxx]的文本后,统一做以下处理:
- 为每个短语生成唯一的翻译键(比如根据文本内容哈希或语义命名)
- 将原始文本(含占位符)存入数据库,同时记录变量映射关系(如
[用户名]对应username) - 后续生成多语言版本时,只需替换对应语言文本中的占位符即可
四、校验补漏
提取完成后运行项目,检查页面是否有遗漏的静态文本,或控制台是否有未处理的内容,手动补全对应的翻译键和文本。
内容的提问来源于stack exchange,提问作者Bohdan Voznyi
相关产品推荐
相关产品推荐

