当前位置: 首页 > news >正文

前端国际化-插件模式

文章目录

  • 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 中引入翻译文件,动态切换语言。

相关文章:

  • Linux网站搭建(新手必看)
  • 项目启动报Error: cannot find module ‘node:path’
  • XXL-Job 处理大数据量并发任务的解决方案及底层原理
  • Java面试黄金宝典15
  • C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)
  • 2、学习Docker前置操作
  • 深度学习框架PyTorch——从入门到精通(10)PyTorch张量简介
  • 第七章:优化热点语句_《C++性能优化指南》_notes
  • Day24:队列的最大值
  • 音视频新人如何快速上手nginx-rtmp-module
  • 人工智能之数学基础:瑞利商的推广形式——广义瑞利商
  • 如何排查C++程序的CPU占用过高的问题
  • Python爬虫:Feapder 的详细使用和案例
  • 在Ubuntu系统上安装连接服务器的图形化界面工具
  • 宏基因组产品升级!污染物降解酶数据库——不只是塑料降解!
  • ubuntu20.04安装教程
  • 网络安全可以考取哪些证书?
  • openGl片段着色器的含义
  • STM32【8】堆栈和段的概念(1)
  • ubuntu20 部署vnc server 使用VNC Viewer连接
  • 今年4月上海一二手房成交面积同比增21%,二手房成交2.07万套
  • 五一期间全国高速日均流量6200万辆,同比增长8.1%
  • 神舟十九号航天员乘组平安抵京
  • 中国人保一季度业绩“分化”:财险净利增超92%,寿险增收不增利
  • 王沪宁主持召开全国政协主席会议
  • 西班牙葡萄牙电力基本恢复