Front-end universal multi-language switching method, device and equipment and medium
By analyzing AST to generate hash identifiers and integrating multilingual translation services in the front-end build tool plug-in, the framework coupling and construction efficiency issues of the front-end multilingual solution are solved, and zero-intrusive multilingual support and efficient maintenance across frameworks are achieved, thereby improving development efficiency.
Patent Information
- Application Number
- CN202511152624.X
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-08-18
- Publication Date
- 2025-09-12
- Estimated Expiration
- Not applicable · inactive patent
AI Technical Summary
Existing front-end multilingual solutions suffer from strong framework coupling, complex translation key management, high intrusiveness in the build phase, and low build efficiency. These problems lead to low development efficiency, inability to reuse across technology stacks, and low automation.
It adopts the framework-independent post-processing principle, analyzes AST during the compilation phase through the build tool plug-in, generates a dynamic unique identifier based on the content hash, integrates multiple third-party translation service APIs, provides a namespace isolation mechanism and a dual-mode translation coverage mechanism, and achieves zero-intrusive development and efficient maintenance.
It achieves cross-framework multi-language support, reduces key name conflict rate, improves build speed, reduces manual intervention, supports seamless integration of enterprise-level micro-frontend architecture, increases build speed by 5.8 times, and reduces manual intervention by 90%.
Smart Images

Figure CN120631494A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the field of front-end engineering, and in particular to a method, device, equipment and medium for universal multi-language switching of a front-end. Background Art
[0002] The current front-end multi-language (i18n) implementation has the following technical flaws:
[0003] 1. Strong framework coupling: Traditional multilingual solutions (such as Vue's vue-i18n and React's react-intl) are deeply dependent on specific frameworks and cannot be reused across technology stacks, resulting in the need to repeatedly implement translation logic in multi-framework projects.
[0004] 2. Complex translation key management: Developers need to manually assign a unique ID to each text, which can easily lead to naming conflicts or omissions (such as duplicate definitions of home.title).
[0005] 3. Highly intrusive during the construction phase: Existing solutions require hard-coding translation functions in the source code, which affects code readability and is difficult to adapt to different technology stacks.
[0006] 4. Low build efficiency: Existing tools cannot accurately identify the scope of text changes and often trigger full recompilation.
[0007] 5. Text extraction, translation, and language pack integration require the collaboration of multiple tools, with manual intervention accounting for up to 60% and a low degree of automation.
[0008] While universal libraries like i18next exist, they still require hard-coded translation functions in the source code and fail to address the pain point of incremental updates. According to the 2023 Front-End Toolchain Survey, multilingual maintenance for large projects takes up an average of 23% of development time. A technical solution is urgently needed that can completely decouple frameworks and automate the entire translation process. Summary of the Invention
[0009] This application provides a method, apparatus, device, and medium for universal multi-language switching on the front-end. It aims to address three core issues: framework coupling, key name management, and build efficiency. It also provides the namespace isolation and dual-mode translation mechanisms essential for enterprise-level multi-language solutions. This multi-language (i18n) solution is applicable to various front-end technology stacks, including Vue, React, pure JavaScript, and TypeScript. It automatically handles the entire translation process during the build phase, enabling zero-intrusive development and efficient maintenance of multi-language projects. The technical solution is as follows:
[0010] In a first aspect, an embodiment of the present application provides a method for front-end universal multi-language switching, comprising: Based on the framework-agnostic post-processing principle, the compiled JavaScript code is processed by the build tool plug-in at the end of the build process; Generate a dynamic unique identifier based on content hash for each text to be translated; Replace the original text node with a translation function call, the translation function taking a dynamic hash identifier as a parameter; Integrate multiple third-party translation service APIs to achieve batch automatic translation processing; Generate a language pack containing the mapping relationship between hash identifiers and multilingual texts; Supports user-defined translation override mechanism, giving priority to custom translation results through user.json file; Provide translation formatting interface to process translation results in real time; Implement a namespace isolation mechanism to resolve language package conflicts during multi-project integration; Identify text nodes to be translated in the source code through abstract syntax tree (AST) analysis; Provide global $t translation function to achieve runtime language switching; Provides active bypass translation mark $$i8n and passive bypass syntax to preserve the original state of specific text; the passive bypass syntax includes console.log, console.warn, require, $t, $i8n, and alert.
[0011] In one embodiment of the above technical solution, the method for generating the dynamic hash identifier includes: Standardize the source text content; Apply the SHA-256 algorithm to generate a fixed-length hash value; The first 6 digits of the hash value are intercepted as a hash prefix, and the hash prefix is combined with a framework type tag to form a final identifier. The framework type tag includes vue_, react_, and js_.
[0012] In one implementation of the above technical solution, the user-defined translation override mechanism includes: Establish priority rules for user-defined translation files and API translation; When a user-defined file is detected, the translation entries in it are matched first; Unmatched texts are automatically processed by calling the translation API; The same Chinese text can generate different translation results in different namespaces.
[0013] In one implementation of the above technical solution, the namespace isolation mechanism includes: Set a unique namespace identifier for each project; The language packs are stored hierarchically by namespace: window.$i8n[namespace][hashKey] = "translation text"; Declare the namespace identifier when injecting the language package twice through the registration function; The runtime implements retrieval path isolation by splicing hash keys with namespace identifiers.
[0014] In one implementation of the above technical solution, the runtime configuration of the build tool plug-in is: Intervene in the final stages of the front-end engineering build process; Analyze the AST structure of the changed module through the difference tree comparison algorithm; Only the text nodes of the incrementally modified part are reprocessed; Automatically ignore hot updates of the i18n output directory to prevent compilation dead loops.
[0015] In one embodiment of the above technical solution, the difference tree comparison algorithm includes: Build a dependency graph of source code modules; Compare the module hash signatures of the two builds; Generate a local AST difference tree for the modified module; Only paths containing text nodes are traversed in the diff tree; An LRU cache mechanism is used to store the AST parsing results of unchanged modules.
[0016] In a second aspect, an embodiment of the present application provides a front-end universal multi-language switching device, comprising: AST parsing module, used to analyze the compiled code structure of various front-end frameworks; Hash generation module, used to create dynamic identifiers tied to text content; Translation proxy module, used to connect to multiple third-party translation service platforms; Namespace router, which directs translation results to isolated storage areas according to configuration; Language pack generator, used to generate resource files that comply with i18n standards; Runtime engine, used to provide runtime support for language switching.
[0017] In one implementation of the above technical solution, the AST parsing module supports: Template and JSX syntax parsing of Vue single-file components; React's JSX syntax tree transformation; Pure JavaScript string literal extraction; Smart ignoring of TypeScript type annotations.
[0018] In a third aspect, an embodiment of the present application further provides an electronic device, including: a memory for storing one or more programs; A processor is used to execute the program stored in the memory to implement a front-end universal multi-language switching method as described in any one of the above items.
[0019] In a fourth aspect, an embodiment of the present application further provides a computer-readable storage medium, on which a computer program is stored. When the computer program is executed by a processor, the method as described in any one of the above items is implemented.
[0020] The core innovations of this application include: 1. Intervene in the final stage of the compilation tool (webpack / vite) construction, automatically identify the text nodes to be translated through AST parsing, and replace the original text with the translation function $t(key), achieving zero source code intrusion; 2. Dynamic key generation algorithm based on content hash (SHA-256 + framework tag); 3. Dual-mode translation coverage mechanism, priority strategy: user.json custom translation > API translation results, translation formatting pipeline: real-time text processing through the formatter interface; 4. Namespace isolation system: Create independent language storage domains through namespace key values, automatically isolate retrieval paths at runtime, and resolve multi-project integration conflicts; 5. Diff tree comparison technology enables precise incremental updates, avoiding full compilation; 6. The multi-service translation proxy module supports seamless switching of APIs such as Google Translate.
[0021] The beneficial effects of the above technical solution include at least: 1. Framework support rate increased to 100% (actual compatibility with Vue2 / 3, React16+, and pure JS / TS projects); 2. The key name conflict rate is reduced to 0% (million-level text stress test); 3. Build speed increased by 5.8 times (measured data from 10,000 lines of code); 4. Reduce manual intervention by 90% (from key name assignment to language pack generation); 5. Enterprise-level extension: The namespace mechanism supports seamless integration of micro-frontend architecture.
[0022] The above summary is for illustrative purposes only and is not intended to be limiting in any way. In addition to the illustrative aspects, embodiments and features described above, further aspects, embodiments and features of the present application will be readily apparent by reference to the accompanying drawings and the following detailed description. BRIEF DESCRIPTION OF THE DRAWINGS
[0023] In order to more clearly illustrate the technical solutions of the embodiments of the present application, the following is a brief introduction to the drawings required for use in the embodiments. In the accompanying drawings, unless otherwise specified, the same reference numerals throughout multiple drawings represent the same or similar parts or elements. These drawings are not necessarily drawn to scale. It should be understood that the following drawings only illustrate certain embodiments of the present application and should not be regarded as limiting the scope. For those of ordinary skill in the art, other relevant drawings can also be obtained based on these drawings without paying creative work.
[0024] Figure 1 This is a flowchart of the steps of a method for universal multi-language switching of a front-end according to an embodiment of the present application; Figure 2 This is a structural block diagram of a front-end universal multi-language switching device according to an embodiment of the present application; Figure 3 This is a comparison diagram of the AST node replacement process in one embodiment of the present application; Figure 4 A flow chart of dynamic hash key generation according to an embodiment of the present application; Figure 5 This is an example of a language package mapping table according to an embodiment of the present application; Figure 6 Schematic diagram of the execution of a difference tree comparison algorithm according to an embodiment of the present application. DETAILED DESCRIPTION
[0025] Hereinafter, only certain exemplary embodiments are briefly described. As will be appreciated by those skilled in the art, the described embodiments may be modified in various ways without departing from the spirit or scope of the present application. Therefore, the drawings and description are to be regarded as illustrative in nature and not restrictive.
[0026] The terms "first", "second", "third" and "fourth" in the specification, claims and drawings of this application are used to distinguish different objects rather than to describe a specific order.
[0027] Reference Figure 1 , showing a flow chart of a method for front-end universal multi-language switching according to an embodiment of the present application, the method comprising:
[0028] Step 1: Use the build tool plug-in to identify the text to be translated based on AST analysis during the compilation phase; During the front-end project compilation process, build tool plugins (such as the Webpack plugin) intervene in the compilation phase. After the build tool initiates compilation, the plugin uses Abstract Syntax Tree (AST) analysis technology to traverse the grammatical structure of the project source code. For syntax files like JSX and Vue templates, it identifies text nodes to be translated and accurately marks content requiring multilingual processing, laying the foundation for subsequent translation.
[0029] Step 2: Generate a unique hash identifier for the text and replace it with the translation function call; For the text to be translated identified in step 1, a hash algorithm is used to generate a unique hash identifier, ensuring that identical text is uniquely identified. The build tool plugin then replaces the original text node with a translation function call, formatted like $t('hash identifier'). This decouples the multilingual text in the source code from the translation logic, allowing the translation function to dynamically load language pack content.
[0030] Step 3: Integrate multiple third-party translation services to achieve batch automatic translation; Based on the collection of text to be translated (including hash identifiers and original text) generated in Step 2, build a tool plug-in or standalone script to integrate multiple third-party translation services (such as the Google Translate API, Youdao Translation API, and Deepl Translation API). By configuring API keys and request parameters, batch translation tasks can be submitted by language type (e.g., Chinese to English, Chinese to Japanese). The translation results are automatically received and parsed, completing the automated production of multilingual copywriting and significantly reducing manual translation costs.
[0031] Step 4: Generate a language pack mapping table and provide a global $t translation function to implement runtime language switching.
[0032] Multilingual text returned by third-party translation services is sorted by language and hash identifier to generate a language pack mapping table ({lang} / index.json, with a data structure of {hash identifier: translated text}). Simultaneously, a global $t translation function is injected into the front-end runtime environment (such as Vue or React frameworks). This function accepts a hash identifier as an input parameter and, based on the current language configuration (which can be stored in global state management, cookies, etc.), matches the corresponding language text from the language pack mapping table and renders it, enabling real-time language switching of page text.
[0033] Reference Figure 2 , showing a structural block diagram of a front-end universal multi-language switching device according to an embodiment of the present application.
[0034] The device is designed based on the principle of framework-independent post-processing. All front-end frameworks (such as Vue, React, etc.) will eventually be compiled into standard JavaScript code. The plug-in processes the final JS code at the end of the build process, without the need to understand the specific framework syntax. The device includes: AST parsing module, used to analyze the compiled code structure of various front-end frameworks; Hash generation module, used to create dynamic identifiers tied to text content; Translation proxy module, used to connect to multiple third-party translation service platforms; Namespace router, which directs translation results to isolated storage areas according to configuration; Language pack generator, used to generate resource files that comply with i18n standards; Runtime engine, used to provide runtime support for language switching.
[0035] Core modules include:
[0036] 1. AST parsing module: implemented based on Babel parser; For .vue files: parse single file components through @vue / compiler-sfc and separate <template> 、 <script>、<style>节点,仅提取<template>中的文本节点;对.jsx / .tsx文件:基于@babel / plugin-syntax-jsx识别JSXText节点及TemplateLiteral(模板字符串),过滤{ / * 注释 * / }中的文本;对.js / .ts文件:解析StringLiteral(字符串字面量),通过预设的excludedCalls列表(如console.log、alert、prompt)跳过被动绕过文本。
[0037] 参照说明书附图3的AST节点替换过程对比图,本系统通过AST解析模块实现中文文本节点的自动化替换,其核心流程包含节点检测→规则过滤→函数调用生成→新节点创建→反向替换五个技术阶段,具体实施步骤包括步骤310-350,如下:
[0038] 步骤310:AST解析器遍历原始代码结构,定位需处理的原始节点。检测逻辑包括:中文文本识别:扫描字符串字面量、注释及JSX文本中的中文字符(如:"登录"、"提交");节点类型标记:识别节点为模板字符串(TemplateLiteral)、JSX文本(JSXText)或调用表达式(CallExpression)。
[0039] 步骤320:AST处理器加载预配置的排除规则集执行安全校验。排除规则集包括:正则排除(excludedPattern):匹配预定义正则表达式(如: / ^[0-9a-zA-Z]+$ / ),跳过纯数字 / 英文文本;函数调用排除(excludedCall):忽略特定函数名关联节点(如:console.log()、alert()、$$i8n())。
[0040] 步骤330:基于过滤结果动态构造翻译函数:函数签名注入:生成标准调用格式$t('哈希值', '命名空间');参数动态绑定:将节点中的中文文本对应的哈希值嵌入函数首个参数,如$t('vue_2k7s9x', '命名空间')。
[0041] 步骤340:根据节点语法类型完成新节点的创建,分为以下两种模式:表达式模式:通过babel中的CallExpression生成完整AST节点;字符串模板模式:直接输出标准函数模板,确保新旧节点执行等价。
[0042] 步骤350:完成原始节点替换闭环。
[0043] 将生成的新节点(函数表达式 / JSX容器节点)映射至原始节点位置;基于更新后的AST树重新生成机器可读代码。
[0044] 2、哈希生成模块:采用SHA-256算法生成内容指纹,动态哈希键生成流程如图4所示。
[0045] 首先对输入的原文本进行标准化处理,确保数据一致性,所述标准化处理包括:移除收尾冗余字符:消除文本开头与末端的空格、制表符等不可见字符;统一换行格式:将CR / LF等混合换行符转换为统一标准(如LF);中文繁简转换:通过GB18030或Unicode映射表实现中文文本的繁简自动转换;SHA-256预运算:对预处理后的文本执行哈希计算,生成哈希值。
[0046] 然后将所述哈希值的前6位作为哈希前缀,将所述哈希前缀与框架类型标记组合形成最终标识符,例如vue_8a3d7f。
[0047] 3、翻译代理模块:采用适配器模式对接多第三方翻译服务,封装GoogleTranslate API(v2)、DeepL API(v1)、百度翻译API的通用接口,支持通过配置动态切换服务(默认优先Google Translate)。
[0048] 如图5所示的语言包映射表示例,最终生成的语言包映射表采用表格形式组织数据。该表包含以下列:
[0049] 第一列(哈希键):存储由哈希生成模块生成的动态哈希键(例如:vue_2k7s9x,react_8d96,js_5e8ff9),作为检索对应翻译项的唯一索引标识符。
[0050] 第二列(原文):、记录源代码中引用的原始文本字符串(例如:"登录”,"提交”,"首页”)。
[0051] 第三列至第N列(译文):根据系统初始化配置参数languages所定义的目标语言列表(例如:en-英文,zh - 中文,ja - 日文),生成相应的翻译文本字符串(例如:"Login” / "ログイン”,"Submit” / "提出する”,"Home” / "ホームページ”)。每新增一种配置语言,即在映射表中对应增加一列译文数据。
[0052] 4、语言包生成器:负责生成与维护多语言资源文件,具体逻辑:输出{lang} / {namespace}.json(如en / product_admin.json),结构为{哈希标识符: 翻译文本};提供自定义翻译加载器(读取{lang} / user.json);命名空间分层:通过window.$i8n[namespace][hashKey]的树形结构存储,例如window.$i8n.product_admin.vue_8a3d7f = "Submit"。
[0053] 为使本领域技术人员实现本方案,以下对实施步骤进行详细说明,包括步骤410-460。
[0054] 步骤410:环境依赖与插件安装前置依赖:Node.js ≥ 14.0.0,npm ≥ 6.0.0 或 yarn ≥ 1.22.0;安装命令:npm install i18n-plugin-plus --save-dev# 或yarn add i18n-plugin-plus --dev
[0055] 步骤420:插件配置全量说明以 Webpack 4.x 为例,完整配置项及默认值如:Import { WebpackI18nPlugin} from 'i18n-plugin-plus'const i18nConfig = { / / 语言包输出目录(必填)i18nDir: path.resolve(__dirname, '. / i18n'), / / 支持的目标语言(必填,至少包含1种)languages: ['en', 'ja', 'fr'], / / 命名空间标识(可选,默认值:'default')nameSpace: 'product_admin', / / 翻译配置(按语言维度设置)translation: {en: { / / 自定义翻译文件路径(可选)userJson: path.resolve(__dirname, '. / i18n / en / user.json'), / / 译文格式化函数(可选)formatter: (val) => val.replace( / \s+ / g, ' ').trim(), / / 去除多余空格 / / 第三方翻译API配置(可选,默认使用Google Translate)api: {type: 'deepl', / / 支持'google' / 'deepl' / 'baidu'apiKey: 'your-deepl-api-key',region: 'us' / / 仅百度翻译需要}},ja: {formatter: (val) => val + '。' / / 日语句尾加句号}}, / / 绕过翻译配置(可选)exclude: { / / 主动绕过标记(默认:'$$i8n')activeMarker: '$$i8n', / / 被动绕过方法列表(默认:['console.log', 'alert'])passiveCalls: ['console.error', 'logger.debug']}, / / 增量编译配置(可选)incremental: { / / 缓存目录(默认:i18nDir / .cache)cacheDir: path.resolve(__dirname, '. / i18n / .cache'), / / LRU缓存大小(默认:1000个模块)lruCacheSize: 2000}}; / / Webpack插件注入module.exports = {plugins: [new WebpackI18nPlugin(i18nConfig)]};
[0056] 步骤430:AST 解析与替换的核心算法1、Vue 模板处理示例<template>欢迎登录<button>{{$$i8n(‘忽略翻译’)}}< / button> <!- 跳过翻译 -->{{ "当前时间:" + date}} <!-- 混合变量的文本 -->< / template>解析与替换过程:识别中的文本"欢迎登录"→生成哈希vue_8f2d1a→替换为{{ $t('vue_8f2d1a')}};跳过$$i8n中的"忽略翻译";识别"当前时间:"→生成哈希vue_3e7c9b→替换为{{ $t('vue_3e7c9b') + date}}。
[0057] 处理后代码:<template>{{ $t('vue_8f2d1a')}}<button>{{$$i8n(‘忽略翻译’)}}< / button> <!- 跳过翻译 -->{{ $t('vue_3e7c9b') + date}} <!-- 混合变量的文本 -->< / template>
[0058] 2、React JSX 处理示例function App() {const title = "首页";return (<h1>{title}< / h1>当前用户:{user.name} <!-- 变量插值,仅翻译固定文本 --><button onClick={() => console.log("提交成功")}>提交< / button>);}
[0059] 解析与替换过程:识别title赋值的"首页"→生成哈希react_5e8ff9→替换为const title = $t('react_5e8ff9');识别中的"当前用户:"→生成哈希react_2a3b4c→替换为{$t('react_2a3b4c') + user.name};识别<button>中的"提交"→生成哈希react_8d969e→替换为<button>...< / button>中的文本;跳过console.log("提交成功")(被动绕过)。
[0060] 处理后代码:function App() {const title = $t('react_5e8ff9');return (<h1>{title}< / h1>{$t('react_2a3b4c') + user.name}<button onClick={() => console.log("提交成功")}>{$t('react_8d969e')}< / button>);}
[0061] 步骤 440:双模式翻译覆盖机制详解1、翻译结果的获取顺序为:用户自定义翻译(user.json)→ 缓存翻译 → 第三方API翻译 → 源文本(降级),流程图如下:输入:源文本 + 目标语言检查user.json中是否存在匹配项?是 → 应用formatter → 返回结果否 → 检查缓存中是否存在翻译?是 → 返回缓存结果否 → 调用第三方API翻译 → 存入缓存 → 应用formatter → 返回结果
[0062] 2、user.json 格式规范[{"vue_8f2d1a": "Welcome to login","react_5e8ff9": "Home Page"}]插件会在构建时自动将 "源文本映射” 转换为 "哈希键映射”,提升运行时查询效率。
[0063] 步骤 450:命名空间隔离与微前端集成当系统采用微前端架构时,会根据每个项目配置的命名空间不同,取到对应空间内的key,避免不同项目相同key值的冲突。以qiankun微前端框架为例,主应用与子应用的配置示例:1、主应用(nameSpace: 'main_app'): / / 主应用Webpack配置new WebpackI18nPlugin({nameSpace: 'main_app',languages: ['en']})2、子应用 1(nameSpace: 'sub_product'): / / 子应用配置new WebpackI18nPlugin({nameSpace: 'sub_product',languages: ['en']})子应用通过$t('vue_123')调用时,自动读取sub_product命名空间下的翻译,避免冲突。
[0064] 步骤460:差异树增量编译:如图6所示的差异树比对算法执行示意图,构建工具启动时,会先加载历史模块哈希表,对比模块哈希前面,若模块未变更,复用缓存AST;若模块变更,重解析变更模块,返回增量AST;这时遍历差异树,做到仅处理变更的文本节点,增量更新语言包。
[0065] 性能对比数据:代码规模在10000行时,全量编译耗时30s,增量编译耗时6s,提升倍数5x;代码规模在50000行时,全量编译耗时160s,增量编译耗时21s,提升倍数7.6x。
[0066] 为实现前端运行时动态切换语言,采用以下技术手段:全局$t函数及语言切换API 的使用示例:1、基础调用: / / 直接调用$t('vue_8f2d1a'); / / 返回当前语言的翻译文本 / / 强制指定语言(忽略全局设置)$t('vue_8f2d1a', 'ja'); / / 返回日语翻译2、切换全局语言: / / 切换为英文window.$i8n.setLanguage('en').then(() => { / / 语言切换后触发视图更新(框架自动适配) / / Vue:this.$forceUpdate() / / React:setState({})});框架适配细节:Vue 项目:通过Vue.mixin在beforeCreate中注入$t方法,语言切换时触发vm.$forceUpdate();React 项目:提供useTranslation钩子,语言切换时通过useState更新状态,触发组件重渲染:import { useTranslation} from 'i18n-plugin-plus / react';function MyComponent() {const { t} = useTranslation();return {t('react_5e8ff9')};}
[0067] 针对无需翻译的特定内容,配置豁免机制如下:1、主动绕过$$i8n / / Vue模板$$i8n(‘原始文本’) / / JSX{$$i8n(‘原始文本’)}2、被动绕过(预设方法): / / console系列方法console.log("调试文本(不翻译)"); / / alert / promptalert("提示文本(不翻译)"); / / 标记为被动绕过的自定义方法 / / (需在配置中添加:exclude.passiveCalls:['logger.log'])logger.log("日志文本(不翻译)");
[0068] 为保障系统健壮性,设置异常处理机制如下:
[0069] 1、翻译 API 调用失败:实现 3 次重试机制(间隔 1s、2s、4s),重试失败后返回源文本,并在i18nDir / error.log中记录错误详情(如 API 密钥失效、网络超时)。
[0070] 2、无效哈希键调用:运行时调用$t('invalid_key')时,返回[Missing Translation: invalid_key],同时在开发环境控制台抛出警告,生产环境静默处理。
[0071] 3、user.json 格式错误:解析失败时(如 JSON 语法错误),插件会忽略该文件并使用 API 翻译,同时在构建日志中输出错误位置(如 "Line 5: Unexpected token}”)。
[0072] 为验证方案通用性,本方案在以下环境进行兼容性测试,并验证通过。
[0073] 框架版本:Vue:2.6.x、3.0.x、3.2.xReact:16.8.x、17.0.x、18.2.x纯 JS / TS:ES5、ES6+构建工具:Webpack:4.x、5.xVite:2.x、3.x
[0074] 本申请实施例还提供了一种电子设备,包括:存储器,用于存储一个或多个程序;处理器,用于执行所述存储器中存储的所述程序,以实现如上述任一项所述的一种前端通用多语言切换的方法。
[0075] 所述电子设备还可以优选地包括通信接口,所述通信接口用于与外部设备进行通信和数据交互传输。
[0076] 需要说明的是,所述存储器可能包含高速RAM存储器,也可能还包括非易失性存储器,例如至少一个磁盘存储器。
[0077] 本申请实施例还提供了一种计算机可读存储介质,存储介质存储有计算机程序,计算机程序被执行时实现上述各方面任一种实施方式中的方法。
[0078] 应当理解,所述计算机可读存储介质为可存储数据或程序的任何数据存储设备,所述数据或程序其后可由计算机系统读取。计算机可读存储介质的示例包括只读存储器、随机存取存储器、CD ROM、HDD、DVD、磁带和光学数据存储设备等。计算机可读存储介质还可分布在网络耦接的计算机系统中使得计算机可读代码以分布式方式来存储和执行。
[0079] 计算机可读存储介质上包含的程序代码可以用任何适当的介质传输,包括但不限于:无线、电线、光缆、射频(Radio Frequency,RF)等,或者上述的任意合适的组合。
[0080] 在一些实施方案中,计算机可读存储介质可以是非暂态的。
[0081] 在上述实施例中,可以全部或部分地通过软件、硬件、固件或者其任意组合来实现。当使用软件实现时,可以全部或部分地以计算机程序产品的形式实现。计算机程序产品包括一个或多个计算机指令。在计算机上加载和执行计算机程序指令时,全部或部分地产生按照本申请的流程或功能。计算机可以是通用计算机、专用计算机、计算机网络、或者其他可编程装置。计算机指令可以存储在计算机可读存储介质中,或者从一个计算机可读存储介质向另一个计算机可读存储介质传输。
[0082] 在本说明书的描述中,流程图中或在此以其他方式描述的任何过程或方法描述可以被理解为,表示包括一个或更多个用于实现特定逻辑功能或过程的步骤的可执行指令的代码的模块、片段或部分。并且本申请的优选实施方式的范围包括另外的实现,其中可以不按所示出或讨论的顺序,包括根据所涉及的功能按基本同时的方式或按相反的顺序,来执行功能。
[0083] 在流程图中表示或在此以其他方式描述的逻辑和 / 或步骤,例如,可以被认为是用于实现逻辑功能的可执行指令的定序列表,可以具体实现在任何计算机可读介质中,以供指令执行系统、装置或设备(如基于计算机的系统、包括处理器的系统或其他可以从指令执行系统、装置或设备取指令并执行指令的系统)使用,或结合这些指令执行系统、装置或设备而使用。
[0084] 最后应说明的是:以上所述实施例,仅为本申请的具体实施方式,用以说明本申请的技术方案,而非对其限制,本申请的保护范围并不局限于此,尽管参照前述实施例对本申请进行了详细的说明,本领域的普通技术人员应当理解:任何熟悉本技术领域的技术人员在本申请揭露的技术范围内,其依然可以对前述实施例所记载的技术方案进行修改或可轻易想到变化,或者对其中部分技术特征进行等同替换;而这些修改、变化或者替换,并不使相应技术方案的本质脱离本申请实施例技术方案的精神和范围,都应涵盖在本申请的保护范围之内。< / script> < / template>
Claims
1. A front-end universal multi-language switching method, characterized in that: include: Based on the framework-agnostic post-processing principle, the compiled JavaScript code is processed by the build tool plug-in at the end of the build process; Generate a dynamic unique identifier based on content hash for each text to be translated; Replace the original text node with a translation function call, the translation function taking a dynamic hash identifier as a parameter; Integrate multiple third-party translation service APIs to achieve batch automatic translation processing; Generate a language pack containing the mapping relationship between hash identifiers and multilingual texts; Supports user-defined translation override mechanism, giving priority to custom translation results through user.json file; Provide translation formatting interface to process translation results in real time; Implement a namespace isolation mechanism to resolve language package conflicts during multi-project integration; Identify text nodes to be translated in the source code through abstract syntax tree (AST) analysis; Provide global $t translation function to achieve runtime language switching; Provides active bypass translation mark $$i8n and passive bypass syntax to preserve the original state of specific text; the passive bypass syntax includes console.log, console.warn, require, $t, $i8n, and alert.
2. The method according to claim 1, characterized in that The method for generating the dynamic hash identifier includes: Standardize the source text content; Apply the SHA-256 algorithm to generate a fixed-length hash value; The first 6 digits of the hash value are intercepted as a hash prefix, and the hash prefix is combined with a framework type tag to form a final identifier. The framework type tag includes vue_, react_, and js_.
3. The method according to claim 1, characterized in that The user-defined translation override mechanism includes: Establish priority rules for user-defined translation files and API translation; When a user-defined file is detected, the translation entries in it are matched first; Unmatched texts are automatically processed by calling the translation API; The same Chinese text can generate different translation results in different namespaces.
4. The method according to claim 1, wherein The namespace isolation mechanism includes: Set a unique namespace identifier for each project; The language packs are stored hierarchically by namespace: window.$i8n[namespace][hashKey] = "translation text"; Declare the namespace identifier when injecting the language package twice through the registration function; The runtime implements retrieval path isolation by splicing hash keys with namespace identifiers.
5. The method according to claim 1, characterized in that The runtime configuration of the build tool plug-in is: Intervene in the final stages of the front-end engineering build process; Analyze the AST structure of the changed module through the difference tree comparison algorithm; Only the text nodes of the incrementally modified part are reprocessed; Automatically ignore hot updates of the i18n output directory to prevent compilation dead loops.
6. The method according to claim 5, characterized in that The difference tree comparison algorithm includes: Build a dependency graph of source code modules; Compare the module hash signatures of the two builds; Generate a local AST difference tree for the modified module; Only paths containing text nodes are traversed in the diff tree; An LRU cache mechanism is used to store the AST parsing results of unchanged modules.
7. A front-end universal multi-language switching device, characterized in that: include: AST parsing module, used to analyze the compiled code structure of various front-end frameworks; Hash generation module, used to create dynamic identifiers tied to text content; Translation proxy module, used to connect to multiple third-party translation service platforms; Namespace router, which directs translation results to isolated storage areas according to configuration; Language pack generator, used to generate resource files that comply with i18n standards; Runtime engine, used to provide runtime support for language switching.
8. The device according to claim 7, characterized in that The AST parsing module supports: Template and JSX syntax parsing of Vue single-file components; React's JSX syntax tree transformation; Pure JavaScript string literal extraction; Smart ignoring of TypeScript type annotations.
9. An electronic device, characterized in that: include: a memory for storing one or more programs; A processor is configured to execute the program stored in the memory to implement a front-end universal multi-language switching method according to any one of claims 1 to 6.
10. A computer-readable storage medium, characterized in that The storage medium stores a computer program, which, when executed by a processor, implements the method according to any one of claims 1 to 6.
Citation Information
Patent Citations
Front-end internationalization multi-language conversion method and system based on vue and webpack
CN115796190A
Function level incremental compiling method and system for software project
CN119248283A
Cited By
Multi-language front-end resource automatic construction method and system based on construction stage
CN121638279A
A multi-language front-end resource automatic construction method and system based on a construction stage
CN121638279B