Vue2存量項目國際化改造踩坑
一、背景
在各類業務場景中,國際化作為非常重要的一部分已經有非常多成熟的方案,但對于一些存量項目則存在非常的改造成本,本文將分享一個的Vue2項目國際化改造方案,通過自定義Webpack插件自動提取中文文本,大大提升改造效率。
二、核心思路
通過開放自定義Webpack插件,利用AST(抽象語法樹)分析技術,自動掃描Vue組件中的中文文本
- 模板中的中文:插值表達式、文本節點、屬性值
- 腳本中的中文:字符串字面量、模板字符串
- 國際化動態注入:通過插件動態替換原中文片段
- 自動生成語言包:輸出標準的i18n語言文件
技術棧
- vue-template-compiler:解析Vue單文件組件
- @babel/parser:解析JavaScript代碼為AST
- @babel/traverse:遍歷AST節點
- Webpack Plugin API:集成到構建流程
三、插件實現
1.插件基礎結構
class MatureChineseExtractorPlugin {constructor(options = {}) {this.options = {outputPath: './i18n',includePatterns: [/src\/.*\.(vue|js|jsx|ts|tsx)$/, '/src/App.vue'],excludePatterns: [/node_modules/,/dist/,/i18n/,/plugins/,/public/,/webpack\.config\.js/,/package\.json/,],methodPrefix: '$smartT',keyPrefix: '',...options,};// 解析結構this.extractedTexts = new Map();// 文件統計this.fileStats = {totalFiles: 0,processedFiles: 0,extractedCount: 0,injectedFiles: 0,skippedFiles: 0,};}/*** 插件入口文件* @param {*} compiler*/apply(compiler) {// 插件主流程}// 插件核心方法// ......
}
2. AST語法樹抽取
apply(compiler) {compiler.hooks.done.tap('MatureChineseExtractorPlugin', (stats) => {const projectRoot = compiler.context;const filePath = path.resolve(projectRoot, './src/App.vue');// 解析Vue組件const content = fs.readFileSync(filePath, 'utf-8');const component = parseComponent(content);// 解析模版AST語法樹const templateAst = compile(component.template.content, {preserveWhitespace: false,whitespace: 'condense',});this.traverseTemplateAST(templateAst.ast, filePath);// 解析Script語法樹const scriptAst = parse(component.script.content, {sourceType: 'module',plugins: ['jsx', 'typescript', 'decorators-legacy', 'classProperties'],});this.traverseScriptAst(scriptAst, filePath);// 替換代碼注入this.injectReplaceCodes();// 輸出結果this.outputResults();});}
3.Vue Template AST解析
/*** 模版AST語法樹處理* @param {AST節點} node*/traverseTemplateAST(node, filePath) {if (!node) return;// 處理元素節點的屬性if (node.type === 1) {// 處理靜態屬性if (node.attrsList) {node.attrsList.forEach((attr) => {if (attr.value && this.containsChinese(attr.value)) {this.addExtractedText(attr.value, filePath, `template-attr-${attr.name}`, {line: node.start || 0,column: 0,});}});}// 處理動態屬性if (node.attrs) {node.attrs.forEach((attr) => {if (attr.value && this.containsChinese(attr.value)) {this.addExtractedText(attr.value, filePath, `template-dynamic-attr-${attr.name}`, {line: 0,column: 0,});}});}}// 處理{{}}表達式節點if (node.type === 2 && node.expression) {// 檢查表達式中是否包含中文字符串const chineseMatches =node.expression.match(/'([^']*[\u4e00-\u9fa5][^']*)'/g) ||node.expression.match(/"([^"]*[\u4e00-\u9fa5][^"]*)"/g) ||node.expression.match(/`([^`]*[\u4e00-\u9fa5][^`]*)`/g);if (chineseMatches) {chineseMatches.forEach((match) => {// 去掉引號const text = match.slice(1, -1);if (this.containsChinese(text)) {this.addExtractedText(text, filePath, 'template-expression', {line: node.start || 0,column: 0,});}});}// 處理模板字符串中的中文if (node.expression.includes('`') && this.containsChinese(node.expression)) {// 簡單提取模板字符串中的中文部分const templateStringMatch = node.expression.match(/`([^`]*)`/);if (templateStringMatch) {const templateContent = templateStringMatch[1];// 提取非變量部分的中文const chineseParts = templateContent.split('${').map((part) => {return part.split('}')[part.includes('}') ? 1 : 0];}).filter((part) => part && this.containsChinese(part));chineseParts.forEach((part) => {this.addExtractedText(part, filePath, 'template-string', {line: node.start || 0,column: 0,});});}}}// 處理文本節點if (node.type === 3 && node.text) {const text = node.text.trim();if (this.containsChinese(text)) {this.addExtractedText(text,filePath,'template-expression',{line: node.start || 0,column: 0,},{oldText: text,newText: `{{${this.options.methodPrefix}('${text}')}}`,});}}// 遞歸處理子節點if (node.children) {node.children.forEach((child) => {this.traverseTemplateAST(child, filePath);});}}
4. Vue Script AST解析
/*** 腳本AST語法樹處理* @param {*} astTree* @param {*} filePath*/traverseScriptAst(astTree, filePath) {traverse(astTree, {// 捕獲所有字符串字面量中的中文StringLiteral: (path) => {const value = path.node.value;if (this.containsChinese(value)) {this.addExtractedText(value, filePath, 'script-string', {line: path.node.loc ? path.node.loc.start.line : 0,column: path.node.loc ? path.node.loc.start.column : 0,});}},// 捕獲模板字符串中的中文TemplateLiteral: (path) => {path.node.quasis.forEach((quasi) => {if (quasi.value.raw && this.containsChinese(quasi.value.raw)) {this.addExtractedText(quasi.value.raw, filePath, 'script-template', {line: quasi.loc ? quasi.loc.start.line : 0,column: quasi.loc ? quasi.loc.start.column : 0,});}});},});}
5. 代碼替換(最小化案例)
/*** 注入替換代碼片段*/injectReplaceCodes() {// 對所有文件分組const injectionMap = new Map();this.extractedTexts.forEach((extractedText) => {const { filePath } = extractedText;if (injectionMap.has(filePath)) {injectionMap.get(filePath).push(extractedText);} else {injectionMap.set(filePath, [extractedText]);}});// 處理每個文件[...injectionMap.keys()].forEach((filePath) => {let content = fs.readFileSync(filePath, 'utf-8');const extractedTextList = injectionMap.get(filePath);for (const extractedText of extractedTextList) {const { text, replaceConfig } = extractedText;// 在遍歷AST樹時,請自行處理if (replaceConfig) {content = content.replace(replaceConfig.oldText, `${replaceConfig.newText}`);} }fs.writeFileSync(filePath, content, 'utf-8');});}
6. 語言包生成
/*** 輸出結果*/outputResults() {const results = Array.from(this.extractedTexts.values());console.log(results);// 生成中文映射文件const chineseMap = {};results.forEach((item) => {chineseMap[item.text] = item.text;});const entries = Object.entries(chineseMap);// 寫入JSON文件const outputFile = path.join(this.options.outputPath, 'extracted-chinese.json');fs.writeFileSync(outputFile, JSON.stringify(chineseMap, null, 2), 'utf-8');// 生成對象屬性字符串const properties = entries.map(([key, value]) => {// 轉義特殊字符const escapedValue = value.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n').replace(/\r/g, '\\r');return ` '${key}': '${escapedValue}'`;}).join(',\n');// 生成zh.js文件const zhJsPath = path.join(this.options.outputPath, 'zh.js');fs.writeFileSync(zhJsPath,`// 自動生成的中文語言包
// 生成時間: ${new Date().toLocaleString()}
// 共提取 ${entries.length} 個中文片段export default {
${properties}
};`,'utf-8');console.log(`提取完成,共提取 ${results.length} 個中文片段`);console.log(`結果已保存到: ${outputFile}`);}
7. 其它輔助方法
/*** 添加提取的文本*/addExtractedText(text, filePath, type, location) {this.extractedTexts.set(text, {text,filePath,type,location,});this.fileStats.extractedCount++;}/*** 檢查是否包含中文*/containsChinese(text) {return /[\u4e00-\u9fa5]/.test(text);}
四、使用方式
1. Webpack配置
// webpack.config.extract.js
const MatureChineseExtractorPlugin = require('./MatureChineseExtractorPlugin');module.exports = {// ... 其他配置plugins: [new MatureChineseExtractorPlugin({outputPath: './i18n',verbose: true})]
};
2. 運行配置
package.json(script)
"extract": "webpack --config webpack.config.extract.js --mode development "
運行
npm run extract
3. 項目案例
<template><div id="app"><header class="header"><h1>{{ '歡迎使用Vue2國際化演示' }}</h1><p>{{ '這是一個完整的國際化解決方案演示項目' }}</p></header><nav class="nav"><button @click="currentView = 'home'" :class="{ active: currentView === 'home' }">{{ '首頁' }}</button><button @click="currentView = 'user'" :class="{ active: currentView === 'user' }">{{ '用戶管理' }}</button><button @click="currentView = 'product'" :class="{ active: currentView === 'product' }">{{ '商品管理' }}</button></nav><main class="main"><div class="status-bar"><span>當前頁面:{{ currentComponent }}</span><span>{{ userInfo.name }},歡迎使用系統</span><span>今天是{{ currentDate }},祝您工作愉快</span></div><component :is="currentComponent"></component></main><footer class="footer"><p>{{ '版權所有 ? 2024 Vue2國際化演示項目' }}</p></footer></div>
</template><script>
import HomePage from './components/HomePage.vue';
import UserManagement from './components/UserManagement.vue';
import ProductManagement from './components/ProductManagement.vue';export default {name: 'App',components: {HomePage,UserManagement,ProductManagement,},data() {return {currentView: 'home',userInfo: {name: '張三',},currentDate: new Date().toLocaleDateString(),};},methods: {sayHello() {console.log('你好,這是一個Vue2國際化改造案例~');},},computed: {currentComponent() {const components = {home: '首頁',user: '用戶管理',product: '商品管理',};return components[this.currentView];},},
};
</script>
4. 提取結果
i18n/
└──zh.js # 中文語言包// 自動生成的中文語言包
// 生成時間: 2025/9/1 11:38:04
// 共提取 12 個中文片段export default {'歡迎使用Vue2國際化演示': '歡迎使用Vue2國際化演示','這是一個完整的國際化解決方案演示項目': '這是一個完整的國際化解決方案演示項目','首頁': '首頁','用戶管理': '用戶管理','商品管理': '商品管理','當前頁面:': '當前頁面:',',歡迎使用系統': ',歡迎使用系統','今天是': '今天是',',祝您工作愉快': ',祝您工作愉快','版權所有 ? 2024 Vue2國際化演示項目': '版權所有 ? 2024 Vue2國際化演示項目','張三': '張三','你好,這是一個Vue2國際化改造案例~': '你好,這是一個Vue2國際化改造案例~'
};
五、總結
通過自定義Webpack插件的方式,我們成功實現了Vue2項目中文文本的自動提取,大大提升了國際化改造的效率。這種基于AST分析的方案不僅準確率高,而且可以靈活擴展,是大型項目國際化改造的理想選擇,而且不僅針對Vue幾乎所有的webpack項目都可以用類似的方案再結合i8n,進行國際化改造~