文章目錄
- Webpack 插件開發
- 解析中文
- 調用有道翻譯 API
- 生成 JSON 語言文件
- React 國際化實現
Webpack 插件開發
- 創建 i18n-webpack-plugin.js 插件:
- 在 src 目錄下掃描所有文件
- 使用 babel-parser 解析 JavaScript/JSX 代碼
- 識別中文文本
- 通過有道翻譯 API 翻譯
- 生成 locales/en.json(英語)和 locales/zh.json(中文)
const fs = require("fs");
const path = require("path");
const parser = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const fetch = require("node-fetch");class I18nWebpackPlugin {constructor(options) {this.options = options || {};this.localeDir = path.resolve(process.cwd(), "locales");this.zhJsonPath = path.join(this.localeDir, "zh.json");this.enJsonPath = path.join(this.localeDir, "en.json");}async extractChinese(content) {const ast = parser.parse(content, { sourceType: "module", plugins: ["jsx"] });const chineseTexts = new Set();traverse(ast, {StringLiteral({ node }) {if (/[\u4e00-\u9fa5]/.test(node.value)) {chineseTexts.add(node.value);}},JSXText({ node }) {if (/[\u4e00-\u9fa5]/.test(node.value.trim())) {chineseTexts.add(node.value.trim());}}});return Array.from(chineseTexts);}async translateText(text) {const apiKey = "your-app-key";const apiSecret = "your-app-secret";const url = `https://openapi.youdao.com/api?q=${encodeURIComponent(text)}&from=zh-CHS&to=en&appKey=${apiKey}`;const response = await fetch(url);const data = await response.json();return data.translation ? data.translation[0] : text;}async apply(compiler) {compiler.hooks.emit.tapAsync("I18nWebpackPlugin", async (compilation, callback) => {const srcDir = path.resolve(process.cwd(), "src");const files = fs.readdirSync(srcDir).filter(file => file.endsWith(".js") || file.endsWith(".jsx"));let translations = {};for (const file of files) {const content = fs.readFileSync(path.join(srcDir, file), "utf-8");const chineseTexts = await this.extractChinese(content);for (const text of chineseTexts) {if (!translations[text]) {translations[text] = await this.translateText(text);}}}if (!fs.existsSync(this.localeDir)) {fs.mkdirSync(this.localeDir);}fs.writeFileSync(this.zhJsonPath, JSON.stringify(translations, null, 2), "utf-8");fs.writeFileSync(this.enJsonPath, JSON.stringify(translations, null, 2), "utf-8");console.log("? 國際化 JSON 文件已生成!");callback();});}
}module.exports = I18nWebpackPlugin;
解析中文
- 使用 babel-parser 解析代碼,提取 JSX 內的中文文本和 JavaScript 代碼中的字符串中文。
調用有道翻譯 API
有道 API 示例:
const fetch = require('node-fetch');async function translate(text, from = 'zh-CHS', to = 'en') {const appKey = 'your-app-key';const appSecret = 'your-app-secret';const url = `https://openapi.youdao.com/api?q=${encodeURIComponent(text)}&from=${from}&to=${to}&appKey=${appKey}`;const response = await fetch(url);const data = await response.json();return data.translation[0]; // 返回翻譯結果
}
生成 JSON 語言文件
掃描所有 src 目錄的文件后,創建 locales/en.json 和 locales/zh.json 語言包,格式如下:
{"首頁": "Home","你好": "Hello"
}
React 國際化實現
- 使用 react-intl 或 i18next 進行國際化支持,并在 App.js 中引入翻譯文件,動態切換語言。