vite-auto-i18n-plugin 1.1.8 → 1.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/package.json +2 -2
  2. package/readme-en.md +0 -591
  3. package/readme.md +0 -603
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-auto-i18n-plugin",
3
- "version": "1.1.8",
3
+ "version": "1.1.9",
4
4
  "description": "Vite automatic translation plugin compatible with Rollup",
5
5
  "keywords": [
6
6
  "i18n",
@@ -33,7 +33,7 @@
33
33
  "@babel/core": "^7.23.2",
34
34
  "@babel/preset-env": "^7.23.2",
35
35
  "@babel/preset-typescript": "^7.23.2",
36
- "auto-i18n-plugin-core": "1.1.8"
36
+ "auto-i18n-plugin-core": "1.1.9"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@babel/types": "^7.23.0",
package/readme-en.md DELETED
@@ -1,591 +0,0 @@
1
- <div align="center">
2
- <img src="./logo.svg" alt="auto-i18n-translation-plugins" width="300">
3
- </div>
4
-
5
- # 🚀 auto-i18n-translation-plugins
6
-
7
- ## 🍉 Plugin Introduction
8
-
9
- A 🎉 **frontend auto-translation plugin** that supports all JavaScript-based frontend frameworks (like Vue2/3 and React). No source code modification needed! Easily achieve multi-language support with one click 🌐🚀. Comes with Youdao and Google translation services by default, while supporting custom translators. Compatible with major build tools like Webpack, Vite, and Rollup.
10
-
11
- ### 🎯 Key Features:
12
-
13
- - 🛠️ **No source code changes** - Quick multi-language translation with one click
14
- - 🌐 **Supports multiple translation services** (Google, Youdao, and custom translators)
15
- - 🔍 **Smart detection** of text needing translation
16
- - 🔧 **Flexible configuration options** for different project needs
17
-
18
- Note: Youdao translation requires users to apply for their translation service - the demo keys have been exhausted.
19
-
20
- ---
21
-
22
- ## 📚 Plugin Debugging
23
-
24
- ```bash
25
- pnpm install
26
- pnpm run build
27
- pnpm run preview // Don't select React, contains too much English text
28
- ```
29
-
30
- ---
31
-
32
- ## 📖 Supported Features
33
-
34
- - **Frameworks**: All JavaScript-based frontend frameworks (Vue2/3, React, etc.)
35
- - **Build Tools**: Fully compatible with Webpack, Vite, and Rollup 🚀
36
- - **Translation Services**: Default support for **Youdao** and **Google** translation, plus custom translators
37
-
38
- ---
39
-
40
- ## ❓ Common Issues
41
-
42
- [Documentation](https://juejin.cn/post/7483435518526062626).
43
-
44
-
45
- ---
46
-
47
- ## 🌟 Quick Start 🚀
48
-
49
- ### 1️⃣ Install Plugin 📦
50
-
51
- #### **🌐 Vite Project:**
52
-
53
- ```bash
54
- npm install vite-auto-i18n-plugin --save-dev
55
- # or
56
- yarn add vite-auto-i18n-plugin --dev
57
- ```
58
-
59
- #### **🛠️ Webpack Project:**
60
-
61
- ```bash
62
- npm install webpack-auto-i18n-plugin --save-dev
63
- # or
64
- yarn add webpack-auto-i18n-plugin --dev
65
- ```
66
-
67
- ---
68
-
69
- ### 2️⃣ Language Switching 🌐
70
-
71
- #### ⚙️ Basic Switching
72
-
73
- ```js
74
- window.localStorage.setItem('lang', value)
75
- window.location.reload()
76
-
77
- // value is the key of the language mapping object
78
- // The mapping object is located in the lang/index.js file by default. You can check this part of the code inside.
79
- const langMap = {
80
- 'en': (),
81
- 'zhcn': ()
82
- }
83
- ```
84
-
85
- #### 📲 Instant Language Switching
86
-
87
- If you don't want to switch languages by refreshing the page, you can directly modify the language via `$changeLang` and then re - render the corresponding components.
88
- ```js
89
- window.$changeLang('en')
90
- ```
91
-
92
- For example, in Vue2, you can switch languages without refreshing the page in the following way:
93
-
94
- ```Html
95
- <template>
96
- <div id="app" v-if="isShow">
97
- <button @click="changeLang('en')">Switch to English</button>
98
- <button @click="changeLang('zh-cn')">Switch to Chinese</button>
99
- <router-view></router-view>
100
- </div>
101
- </template>
102
- <script>
103
- export default {
104
- data() {
105
- return {
106
- isShow: true
107
- }
108
- },
109
- methods: {
110
- changeLang(lang) {
111
- window.$changeLang(lang)
112
- this.isShow = false
113
- this.$nextTick(() => {
114
- this.isShow = true
115
- })
116
- }
117
- }
118
- }
119
- </script>
120
- ```
121
- #### 🔄 Replace Language Packs
122
-
123
- If you want to modify the built - in generated language packs, you can directly modify the `langMap` in the global object. For example:
124
-
125
- ```js
126
- window.langMap = {
127
- 'en': {
128
- 'zccsau6': 'hello'
129
- },
130
- 'zh-cn': {
131
- 'zccsau6': '你好'
132
- }
133
- }
134
- ```
135
-
136
- Then you can refresh the page by using the above **Instant Language Switching** method.
137
-
138
- ---
139
-
140
- ### 3️⃣ Basic Configuration 🔧
141
-
142
- #### **Vite Configuration Example** (vite.config.js):
143
-
144
- ```javascript
145
- import vitePluginsAutoI18n, { YoudaoTranslator } from 'vite-auto-i18n-plugin'
146
- import vue from '@vitejs/plugin-vue'
147
- import { defineConfig } from 'vite'
148
-
149
- export default defineConfig({
150
- plugins: [
151
- vue({
152
- template: {
153
- compilerOptions: {
154
- hoistStatic: false,
155
- cacheHandlers: false
156
- }
157
- }
158
- }),
159
- vitePluginsAutoI18n({
160
- translator: new YoudaoTranslator({
161
- appId: '4cdb9baea8066fef',
162
- appKey: 'ONI6AerZnGRyDqr3w7UM730mPuF8mB3j'
163
- })
164
- })
165
- ]
166
- })
167
- ```
168
- #### **Webpack Configuration Example** (webpack.config.js):
169
-
170
- ```javascript
171
- const webpackPluginsAutoI18n = require('webpack-auto-i18n-plugin')
172
- const { YoudaoTranslator } = require('webpack-auto-i18n-plugin')
173
-
174
- const i18nPlugin = new webpackPluginsAutoI18n.default({
175
- translator: new YoudaoTranslator({
176
- appId: '4cdb9baea8066fef',
177
- appKey: 'ONI6AerZnGRyDqr3w7UM730mPuF8mB3j'
178
- })
179
- })
180
-
181
- module.exports = {
182
- plugins: [
183
- new VueLoaderPlugin(),
184
- new HtmlWebpackPlugin({
185
- template: './public/index.html'
186
- }),
187
- i18nPlugin
188
- ]
189
- }
190
- ```
191
-
192
- ---
193
- ### 4️⃣ Translator Configuration Examples 🛠️
194
-
195
- The plugin uses Google Translate by default (with a default proxy port of 7890). When the network does not support accessing Google, we recommend using **Youdao Translate** ✨, which has excellent translation quality. Currently, the plugin has built - in support for Google, Youdao, and Baidu translation services. If you need to customize a translator, you can refer to the examples below.
196
-
197
- The following examples use `vite` as an example, and `webpack` is similar.
198
-
199
- #### **Using Google Translate (Default)**
200
-
201
- ```javascript
202
- import { GoogleTranslator } from 'vite-auto-i18n-plugin'
203
-
204
- ...
205
- translator: new GoogleTranslator({
206
- proxyOption: {
207
- host: '127.0.0.1',
208
- port: 7890,
209
- headers: {
210
- 'User-Agent': 'Node'
211
- }
212
- }
213
- })
214
- ...
215
- ```
216
- #### **Using Youdao Translation**
217
-
218
- You need to apply for an API. [API documentation](https://ai.youdao.com/DOCSIRMA/html/trans/api/wbfy/index.html).
219
- ```javascript
220
- import { YoudaoTranslator } from 'vite-auto-i18n-plugin'
221
-
222
- ...
223
- translator: new YoudaoTranslator({
224
- appId: 'The appId you applied for',
225
- appKey: 'The appKey you applied for'
226
- })
227
- ...
228
- ```
229
-
230
- #### **Baidu Translator**
231
-
232
- You need to apply for an API. [API documentation](https://api.fanyi.baidu.com/product/113).
233
-
234
- ```javascript
235
- import { BaiduTranslator } from 'vite-auto-i18n-plugin'
236
-
237
- ...
238
- translator: new BaiduTranslator({
239
- appId: 'The appId you applied for', // Baidu Translate AppId
240
- appKey: 'The appKey you applied for' // Baidu Translate AppKey
241
- })
242
- ...
243
- ```
244
-
245
- #### **Volcengine AI Translator**
246
-
247
- It supports translation using `doubao` or `deepseek`. The translation effect of large AI models is more accurate than traditional API translation, but it takes longer.
248
- Introduction to Volcengine large models: https://www.volcengine.com/docs/82379/1099455.
249
- You need to activate the large model service and apply for an API. [API documentation](https://www.volcengine.com/docs/82379/1298454).
250
- ```javascript
251
- import { VolcengineTranslator } from 'vite-auto-i18n-plugin'
252
-
253
- ...
254
- translator: new VolcengineTranslator({
255
- apiKey: 'The apiKey you applied for',
256
- model: 'The model you want to call, for example: `doubao-1-5-pro-32k-250115`. Please ensure that the corresponding model has been activated in the console before use.'
257
- })
258
- ...
259
- ```
260
-
261
- #### **Empty Translator**
262
-
263
- If you only need to scan the target language without performing translation, this translator will generate a JSON file.
264
-
265
- ```javascript
266
- import { EmptyTranslator } from 'vite-auto-i18n-plugin'
267
-
268
- ...
269
- translator: new EmptyTranslator()
270
- ...
271
- ```
272
- #### **Custom Translator**
273
-
274
- If you have a personal translation API, you can customize a translator in the following ways:
275
-
276
- The simplest way is to define a translator instance using the `Translator` base class.
277
-
278
- ```javascript
279
- import { Translator } from 'vite-auto-i18n-plugin'
280
- import axios from 'axios'
281
-
282
- ...
283
- translator: new Translator({
284
- name: 'My Translator',
285
- // Translation method
286
- fetchMethod: (str, fromKey, toKey, _separator) => {
287
- // The actual API call may be more complex than the example. For details, please refer to the implementation of YoudaoTranslator in the source code. Path: packages\autoI18nPluginCore\src\translators\youdao.ts
288
- const myApi = 'https://www.my-i18n.cn/api/translate?from=${fromKey}&to=${toKey}&t={+new Date}'
289
- return axios.post(myApi, { str })
290
- .then(res => res.data)
291
- },
292
- // Interface trigger interval. Some interfaces may be blocked if triggered frequently. Please set a reasonable interface trigger interval according to the actual situation.
293
- interval: 1000
294
- })
295
- ...
296
- ```
297
- If you need more advanced features, you can use inheritance. However, there is currently no relevant scenario.
298
- ```javascript
299
- import { Translator } from 'vite-auto-i18n-plugin'
300
-
301
- class CustomTranslator extends Translator {
302
- constructor () {
303
- super({
304
- name: 'My Translator',
305
- ...
306
- })
307
- }
308
- }
309
-
310
- ...
311
- translator: new CustomTranslator()
312
- ...
313
- ```
314
-
315
- ---
316
-
317
- ### 5️⃣ Project Entry Configuration 🏗️
318
-
319
- Please import the language configuration file at the top of the **project entry file** (e.g., `main.js`):
320
-
321
- ```javascript
322
- import '../lang/index.js' // 📍 Must be imported on the first line of the entry file. The file will be automatically generated when the plugin is run. By default, it is located in the 'lang' folder at the same level as the packaging configuration directory. The 'index.js' inside is the configuration file.
323
- ```
324
-
325
- ---
326
-
327
- ## ⚙️ Configuration Parameters
328
-
329
- | Parameter | Type | Required | Default | Description |
330
- | -------------------- | ---------- | -------- | ------------------------ | -------------------------------------------------------- |
331
- | enabled | boolean | ❌ | `true` | Whether to trigger translation. |
332
- | translateType | string | ❌ | `full-auto` | Translation mode: `full-auto` or `semi-auto` |
333
- | translateKey | string | ✅ | `$t` | Translation function name (e.g., `$t`) |
334
- | excludedCall | string[] | ❌ | `['$i8n', 'require', …]` | Function calls to exclude from translation |
335
- | excludedPattern | RegExp[] | ❌ | `[/\.\w+$/]` | Patterns to exclude (e.g., file extensions) |
336
- | excludedPath | string[] | ❌ | `['node_modules']` | Directories to exclude (e.g., `node_modules`) |
337
- | includePath | RegExp[] | ❌ | `[/src\//]` | Whitelist of directories to include (default: `src`) |
338
- | globalPath | string | ❌ | `'./lang'` | Path for translation config files |
339
- | distPath | string | ✅ | `''` | Output path for built files |
340
- | distKey | string | ✅ | `'index'` | Main translation file name |
341
- | namespace | string | ✅ | `lang` | Project namespace for distinguishing translation configs |
342
- | originLang | string | ✅ | `'zh-cn'` | Source language |
343
- | targetLangList | string[] | ✅ | `['en']` | Target languages |
344
- | buildToDist | boolean | ❌ | `false` | Whether to bundle translation files into main build |
345
- | translator | Translator | ❌ | `GoogleTranslator` | Translator instance |
346
- | translatorOption | object | ❌ | `{}` | Translator options (lower priority than `translator`) |
347
- | rewriteConfig | boolean | ❌ | `true` | Whether to rewrite config file on each plugin run |
348
- | deepScan | boolean | ❌ | `false` | Experimental: Whether to perform deep string scanning |
349
- | commonTranslateKey | string | ❌ | `''` | General translation key |
350
- | insertFileExtensions | string[] | ❌ | `[]` | List of file extensions to insert translation code into |
351
- | isClear | boolean | ❌ | `false` | Whether to clear content not in context (clear source language key-value pairs not in context), only supported in build mode |
352
- | isClearSpace | boolean | ❌ | `false` | Whether to remove whitespace from both ends of source strings, whitespace is preserved by default |
353
-
354
- ---
355
-
356
- ## 🔍 What does `deepScan` do?
357
-
358
- `deepScan` is an experimental property controlling whether the plugin performs deep string scanning.
359
-
360
- By default, the plugin scans strings/template strings - if any target language text is found, the entire string is included:
361
-
362
- ```js
363
- ;`<div>
364
- <p>你好</p>
365
- </div>`
366
- ```
367
-
368
- Since there's Chinese text, the whole string would be included, potentially causing inaccurate translation. With `deepScan` enabled, the plugin splits and reconstructs template strings, only translating matching text:
369
-
370
- ```js
371
- ;`<div>
372
- <p>${$t('你好')}</p>
373
- </div>`
374
- ```
375
-
376
- Now only '你好' gets translated, not the entire string.
377
-
378
- ---
379
-
380
- ## 👋 `translateType` Functionality
381
-
382
- Added in v1.0.11, with two options:
383
-
384
- `full-auto`: Fully automatic translation (default supports Chinese, Japanese, Korean, Russian)
385
-
386
- `semi-auto`: Semi-automatic translation (supports all source languages)
387
-
388
- In `semi-auto` mode, users must wrap target text with `translateKey` (e.g., `$t('hello')`), which the plugin will then translate.
389
-
390
- Example:
391
-
392
- ```js
393
- const HelloWorld: React.FC<HelloWorldProps> = ({ name = 'World' }) => {
394
- return (
395
- <div className="hello-world">
396
- <h1>
397
- {$t('Hello,')} {name}!
398
- </h1>
399
- <p>{$t('Welcome to our application')}</p>
400
- </div>
401
- )
402
- }
403
- ```
404
-
405
- ---
406
-
407
- ## ❓ Why `buildToDist`?
408
-
409
- In Vite, the plugin only generates translation config files. Without `buildToDist`, these files won't be bundled. ⚠️ Enabling this bundles them but may create duplicate config files.
410
-
411
- ---
412
-
413
- ## 🔄 How to Update Translations?
414
-
415
- After running the plugin, two files are generated in `\lang`:
416
-
417
- - **index.js**: Translation function logic
418
- - **index.json**: Translation content
419
-
420
- To update translations, simply modify `index.json`.
421
-
422
- ---
423
-
424
- ## ⚠️ Usage Notes
425
-
426
- 1. **Proxy Requirements**
427
-
428
- - In China, **Youdao Translate** is strongly recommended
429
- - Google Translate requires proxy configuration
430
- - Default proxy port: **7890** (customizable via `proxyOption`)
431
-
432
- 2. **Translation Frequency**
433
-
434
- - Google Translate is free but may limit frequent requests 🔒
435
- - Set reasonable intervals between requests 💡
436
-
437
- 3. **Translation Updates**
438
- - `index.json` in `globalPath` is the core translation file
439
- - Changes take effect immediately after saving
440
-
441
- ---
442
-
443
- ## 📦 User Group
444
-
445
- WeChat Group
446
-
447
- ![wx](./wx.jpg)
448
-
449
- ---
450
-
451
- ## 📦 Example Project
452
-
453
- Example project: [example](./example) (click to view)
454
-
455
- ## 📜 License
456
-
457
- MIT License 🪪 - Free to use and contribute!
458
-
459
- May this plugin make your i18n development easier and more efficient! 🌍✨
460
-
461
- ---
462
-
463
- ## ✨ Update
464
-
465
- Since v1.0.5, simply import the generated `index.js` in your entry file - no need to manually create language switching functions. 👏
466
-
467
- ---
468
-
469
- ## 🎆 Authors
470
-
471
- Original authors: wenps, xu-code, Caleb-Xu, Winfans
472
-
473
- ## Changelog
474
-
475
-
476
- ### v1.1.8 (Recommended Version)
477
-
478
- - Renamed configuration for controlling leading/trailing whitespace removal
479
-
480
- ### v1.1.7 (Recommended Version)
481
-
482
- - Added compatibility for enable feature and translation initialization completion
483
- - Added configuration option to control whether to remove leading/trailing whitespace during scanning
484
- - Fixed issue with abnormal triggering of new translations
485
- - Fixed issue where cleanup configuration was not taking effect
486
-
487
- ### v1.1.6 (Recommended Version)
488
-
489
- - Fixed issue where clearing whitespace before/after template strings caused mismatch between JSON and translation functions
490
- - Fixed issue where Chinese brackets in interpolation caused interpolation to fail
491
- - Added configuration cleanup functionality
492
-
493
- ### v1.1.5 (Recommended Version)
494
-
495
- - Added support for interpolation translation
496
-
497
- ### v1.1.4 (Recommended Version)
498
-
499
- - Fixed template string processing exception in exclude functions
500
- - Added interval configuration for Google Translate
501
- - Added support for custom interface parameters in translators
502
-
503
-
504
- ### v1.1.3 (Recommended Version)
505
-
506
- - Added the ability to update languages without refreshing and best practices
507
-
508
- ### v1.1.2
509
-
510
- - Fixed AI translation exceptions
511
-
512
- ### v1.1.1
513
-
514
- - New translation disable function
515
-
516
- ### v1.1.0
517
-
518
- - New AI translator
519
- - New Vue2 extension plugin mechanism for translation plugins
520
-
521
- ### v1.0.26 (Recommended Version)
522
-
523
- - Added custom extension arrays
524
-
525
- ### v1.0.25 (Recommended Version)
526
-
527
- - Added a universal translation key
528
-
529
- ### v1.0.24 (Recommended Version)
530
-
531
- - Fixed the exception issue in semi-automatic mode
532
-
533
- ### v1.0.23 (Recommended Version)
534
-
535
- - Fixed a major bug in packaging and writing.
536
-
537
- ### v1.0.22
538
-
539
- - Added scan translator
540
-
541
- ### v1.0.21
542
-
543
- - Added deep scanning
544
-
545
- ### v1.0.20
546
-
547
- - Fixed filter function issues and added config overwrite option
548
-
549
- ### v1.0.19
550
-
551
- - Backward compatibility for config files
552
-
553
- ### v1.0.18
554
-
555
- - Fixed optional chaining issues in older Node versions
556
-
557
- ### v1.0.17
558
-
559
- - Basic SSR support (experimental)
560
-
561
- ### v1.0.16
562
-
563
- - Fixed Vue3 comment node issues
564
-
565
- ### v1.0.15
566
-
567
- - Added Baidu Translate
568
-
569
- ### v1.0.14
570
-
571
- - Fixed new language type segmentation
572
- - Added Japanese, Korean, Russian support
573
-
574
- ### v1.0.13
575
-
576
- - Bug fixes
577
-
578
- ### v1.0.12
579
-
580
- - Type optimizations
581
-
582
- ### v1.0.11
583
-
584
- - Bug fixes
585
- - Added `translateType` option for semi-auto mode
586
-
587
- ```js
588
- // Users can wrap text with translateKey
589
- // e.g., $t('hello') - plugin will scan and translate these
590
- $t('hello')
591
- ```
package/readme.md DELETED
@@ -1,603 +0,0 @@
1
- <div align="center">
2
- <img src="./logo.svg" alt="auto-i18n-translation-plugins" width="300">
3
- </div>
4
-
5
- # 🚀 auto-i18n-translation-plugins
6
-
7
- [English Documentation](./readme-en.md)
8
-
9
- ## 🍉 插件介绍
10
-
11
- 一个 🎉 **前端自动翻译插件**,支持所有编译成 JS 的前端框架(例如 Vue2/3 和 React)。无需修改源码,通过支持多种翻译服务,一键轻松实现多语言支持!🌐🚀 默认集成有道翻译和谷歌翻译,同时支持自定义翻译器,兼容 Webpack、Vite、Rollup 等主流构建工具。
12
-
13
- ### 🎯 核心优势:
14
-
15
- - 🛠️ **无需改动源码**,一键快速翻译多语言;
16
- - 🌐 **支持多种翻译服务**(包括 Google 和有道,及自定义翻译器);
17
- - 🔍 **智能检测**需要翻译的文本;
18
- - 🔧 提供 **灵活的配置选项**,满足不同项目需求。
19
-
20
- tips:有道翻译需要用户自己去申请有道的翻译服务,demo里面的key已经被用完了。
21
-
22
- ---
23
-
24
- ## 📚 插件调试
25
-
26
- ```bash
27
- pnpm install
28
- pnpm run build
29
- pnpm run preview // 别选react,里面太多英文不好扫
30
- ```
31
-
32
- ---
33
-
34
- ## 📖 支持范围
35
-
36
- - **框架**: 支持所有编译为 JS 的前端框架(如 Vue2/3 和 React 等)。
37
- - **构建工具**: 完美兼容 Webpack、Vite 和 Rollup 🚀。
38
- - **翻译服务**: 默认支持 **有道翻译** 和 **谷歌翻译**,并支持自定义翻译器。
39
-
40
- ---
41
-
42
- ## ❓ 常见问题
43
-
44
- [问题文档](https://juejin.cn/post/7483435518526062626)。
45
-
46
- ---
47
-
48
- ## 🌟 快速开始 🚀
49
-
50
- ### 1️⃣ 安装插件 📦
51
-
52
- #### **🌐 Vite 项目:**
53
-
54
- ```bash
55
- npm install vite-auto-i18n-plugin --save-dev
56
- # 或
57
- yarn add vite-auto-i18n-plugin --dev
58
- ```
59
-
60
- #### **🛠️ Webpack 项目:**
61
-
62
- ```bash
63
- npm install webpack-auto-i18n-plugin --save-dev
64
- # 或
65
- yarn add webpack-auto-i18n-plugin --dev
66
- ```
67
-
68
- ---
69
-
70
- ### 2️⃣ 语言切换 🌐
71
-
72
- #### ⚙️ 基础切换
73
-
74
- ```js
75
- window.localStorage.setItem('lang', value)
76
- window.location.reload()
77
-
78
- // value 是 语言映射对象 的 key 值
79
- // 映射对象默认存在于 lang/index.js 文件下,可以看里面的这部分代码
80
- const langMap = {
81
- 'en': (),
82
- 'zhcn': ()
83
- }
84
- ```
85
-
86
- #### 📲 即时切换语言
87
-
88
- 如果不想通过页面刷新来切换语言,可以直接通过 `$changeLang` 来修改语言,再重新渲染对应组件
89
-
90
- ```js
91
- window.$changeLang('en')
92
- ```
93
-
94
- 例如在 Vue2 中,可以通过以下方式进行语言无刷切换:
95
-
96
- ```Html
97
- <template>
98
- <div id="app" v-if="isShow">
99
- <button @click="changeLang('en')">切换到英文</button>
100
- <button @click="changeLang('zh-cn')">切换到中文</button>
101
- <router-view></router-view>
102
- </div>
103
- </template>
104
- <script>
105
- export default {
106
- data() {
107
- return {
108
- isShow: true
109
- }
110
- },
111
- methods: {
112
- changeLang(lang) {
113
- window.$changeLang(lang)
114
- this.isShow = false
115
- this.$nextTick(() => {
116
- this.isShow = true
117
- })
118
- }
119
- }
120
- }
121
- </script>
122
- ```
123
-
124
- #### 🔄 替换语言包
125
-
126
- 如果想修改内置生成的语言包,可以直接修改全局对象里面的 langMap,例如:
127
-
128
- ```js
129
- window.langMap = {
130
- en: {
131
- zccsau6: 'hello'
132
- },
133
- 'zh-cn': {
134
- zccsau6: '你好'
135
- }
136
- }
137
- ```
138
-
139
- 然后再通过上述的**即时切换语言**的方式进行刷新即可。
140
-
141
- ---
142
-
143
- ### 3️⃣ 基础配置 🔧
144
-
145
- #### **Vite 配置示例** (vite.config.js):
146
-
147
- ```javascript
148
- import vitePluginsAutoI18n, { YoudaoTranslator } from 'vite-auto-i18n-plugin'
149
- import vue from '@vitejs/plugin-vue'
150
- import { defineConfig } from 'vite'
151
-
152
- export default defineConfig({
153
- plugins: [
154
- vue({
155
- template: {
156
- compilerOptions: {
157
- hoistStatic: false,
158
- cacheHandlers: false
159
- }
160
- }
161
- }),
162
- vitePluginsAutoI18n({
163
- translator: new YoudaoTranslator({
164
- appId: '4cdb9baea8066fef',
165
- appKey: 'ONI6AerZnGRyDqr3w7UM730mPuF8mB3j'
166
- })
167
- })
168
- ]
169
- })
170
- ```
171
-
172
- #### **Webpack 配置示例** (webpack.config.js):
173
-
174
- ```javascript
175
- const webpackPluginsAutoI18n = require('webpack-auto-i18n-plugin')
176
- const { YoudaoTranslator } = require('webpack-auto-i18n-plugin')
177
-
178
- const i18nPlugin = new webpackPluginsAutoI18n.default({
179
- translator: new YoudaoTranslator({
180
- appId: '4cdb9baea8066fef',
181
- appKey: 'ONI6AerZnGRyDqr3w7UM730mPuF8mB3j'
182
- })
183
- })
184
-
185
- module.exports = {
186
- plugins: [
187
- new VueLoaderPlugin(),
188
- new HtmlWebpackPlugin({
189
- template: './public/index.html'
190
- }),
191
- i18nPlugin
192
- ]
193
- }
194
- ```
195
-
196
- ---
197
-
198
- ### 4️⃣ 翻译器配置示例 🛠️
199
-
200
- 插件默认使用谷歌翻译(默认配置代理端口7890)。在网络不支持访问谷歌的情况下,我们推荐使用 **有道翻译** ✨,其翻译效果优秀。目前插件已经内置谷歌、有道和百度翻译功能。如果需要自定义翻译器,可参考下方的示例。
201
-
202
- 以下示例以 `vite` 为例,`webpack` 与其类似。
203
-
204
- #### **使用谷歌翻译(默认)**
205
-
206
- ```javascript
207
- import { GoogleTranslator } from 'vite-auto-i18n-plugin'
208
-
209
- ...
210
- translator: new GoogleTranslator({
211
- proxyOption: {
212
- host: '127.0.0.1',
213
- port: 7890,
214
- headers: {
215
- 'User-Agent': 'Node'
216
- }
217
- }
218
- })
219
- ...
220
- ```
221
-
222
- #### **使用有道翻译**
223
-
224
- 需要申请api,[api文档](https://ai.youdao.com/DOCSIRMA/html/trans/api/wbfy/index.html)。
225
-
226
- ```javascript
227
- import { YoudaoTranslator } from 'vite-auto-i18n-plugin'
228
-
229
- ...
230
- translator: new YoudaoTranslator({
231
- appId: '你申请的appId',
232
- appKey: '你申请的appKey'
233
- })
234
- ...
235
- ```
236
-
237
- #### **百度翻译器**
238
-
239
- 需要申请api,[api文档](https://api.fanyi.baidu.com/product/113)。
240
-
241
- ```javascript
242
- import { BaiduTranslator } from 'vite-auto-i18n-plugin'
243
-
244
- ...
245
- translator: new BaiduTranslator({
246
- appId: '你申请的appId', // 百度翻译 AppId
247
- appKey: '你申请的appKey' // 百度翻译 AppKey
248
- })
249
- ...
250
- ```
251
-
252
- #### **火山引擎AI翻译器**
253
-
254
- 支持调用 `doubao` 或 `deepseek` 进行翻译,AI大模型的翻译效果会比传统的API翻译更准确,但耗时较长。
255
- 火山引擎大模型介绍:https://www.volcengine.com/docs/82379/1099455。
256
- 需要开通大模型服务并申请API,[api文档](https://www.volcengine.com/docs/82379/1298454)。
257
-
258
- ```javascript
259
- import { VolcengineTranslator } from 'vite-auto-i18n-plugin'
260
-
261
- ...
262
- translator: new VolcengineTranslator({
263
- apiKey: '你申请的apiKey',
264
- model: '你要调用的模型,如:`doubao-1-5-pro-32k-250115`,请确保使用前已在控制台开通了对应模型'
265
- })
266
- ...
267
- ```
268
-
269
- #### **空翻译器**
270
-
271
- 如果只需要扫描目标语言,不进行翻译,该翻译器会生成 JSON 文件。
272
-
273
- ```javascript
274
- import { EmptyTranslator } from 'vite-auto-i18n-plugin'
275
-
276
- ...
277
- translator: new EmptyTranslator()
278
- ...
279
- ```
280
-
281
- #### **自定义翻译器**
282
-
283
- 如果你有一个自用的翻译接口,可以通过以下方式自定义翻译器——
284
-
285
- 最简单的方式是使用 `Translator` 基类定义翻译器实例。
286
-
287
- ```javascript
288
- import { Translator } from 'vite-auto-i18n-plugin'
289
- import axios from 'axios'
290
-
291
- ...
292
- translator: new Translator({
293
- name: '我的翻译器',
294
- // 翻译的方法
295
- fetchMethod: (str, fromKey, toKey, _separator) => {
296
- // 实际的接口调用可能比示例更复杂,具体可参考源码中YoudaoTranslator的实现,路径:packages\autoI18nPluginCore\src\translators\youdao.ts
297
- const myApi = 'https://www.my-i18n.cn/api/translate?from=${fromKey}&to=${toKey}&t={+new Date}'
298
- return axios.post(myApi, { str })
299
- .then(res => res.data)
300
- },
301
- // 接口触发间隔,有些接口频繁触发会被拉黑,请根据实际情况设置一个合理的接口触发间隔
302
- interval: 1000
303
- })
304
- ...
305
- ```
306
-
307
- 如果需要更高阶的功能,可以使用继承,不过目前无相关场景。
308
-
309
- ```javascript
310
- import { Translator } from 'vite-auto-i18n-plugin'
311
-
312
- class CustomTranslator extends Translator {
313
- constructor () {
314
- super({
315
- name: '我的翻译器',
316
- ...
317
- })
318
- }
319
- }
320
-
321
- ...
322
- translator: new CustomTranslator()
323
- ...
324
- ```
325
-
326
- ---
327
-
328
- ### 5️⃣ 项目入口配置 🏗️
329
-
330
- 请在**项目入口文件**(如 `main.js`)的顶部引入语言配置文件:
331
-
332
- ```javascript
333
- import '../lang/index.js' // 📍 必须在入口文件中第一行引入,文件会在运行插件时自动生成,默认位于打包配置目录同层的lang文件夹中,其中的index.js就是配置文件
334
- ```
335
-
336
- ---
337
-
338
- ## ⚙️ 配置参数说明
339
-
340
- | 参数 | 类型 | 必选 | 默认值 | 描述 |
341
- | -------------------- | ---------- | ---- | ------------------------ | ------------------------------------------------------------------ |
342
- | enabled | boolean | ❌ | `true` | 是否触发翻译。 |
343
- | translateType | string | ❌ | `full-auto` | 翻译状态,默认有两种可选`full-auto` 和 `semi-auto` 。 |
344
- | translateKey | string | ✅ | `$t` | 翻译调用函数名称,例如`$t` 表示翻译调用时的函数名 |
345
- | excludedCall | string[] | ❌ | `['$i8n', 'require', …]` | 标记不会被翻译的函数调用列表 |
346
- | excludedPattern | RegExp[] | ❌ | `[/\.\w+$/]` | 用于标记排除不翻译的字符串模式,例如文件路径中的文件后缀 |
347
- | excludedPath | string[] | ❌ | `['node_modules']` | 指定需要排除翻译的文件夹路径,例如默认会跳过`node_modules` |
348
- | includePath | RegExp[] | ❌ | `[/src\//]` | 指定只翻译某些目录路径(白名单),默认为`src` |
349
- | globalPath | string | ❌ | `'./lang'` | 翻译文件配置生成路径 |
350
- | distPath | string | ✅ | `''` | 打包后生成的文件位置路径 |
351
- | distKey | string | ✅ | `'index'` | 打包后生成的翻译主文件名称 |
352
- | namespace | string | ✅ | `lang` | 项目命名空间,用于区分不同项目的翻译配置 |
353
- | originLang | string | ✅ | `'zh-cn'` | 源语言,翻译以此语言为基础 |
354
- | targetLangList | string[] | ✅ | `['en']` | 目标语言列表,支持配置多个语言 |
355
- | buildToDist | boolean | ❌ | `false` | 是否在构建结束后将最新的翻译文件打包到主包中,默认不打包 |
356
- | translator | Translator | ❌ | `GoogleTranslator` | 翻译器实例 |
357
- | translatorOption | object | ❌ | `{}` | 翻译器的配置项,优先级低于`translator` |
358
- | rewriteConfig | boolean | ❌ | `true` | 插件每次运行时是否重写配置文件 |
359
- | deepScan | boolean | ❌ | `false` | 实验性属性,表示是否进行深层扫描字符串 |
360
- | commonTranslateKey | string | ❌ | `''` | 通用翻译key |
361
- | insertFileExtensions | string[] | ❌ | `[]` | 要插入翻译代码的文件扩展名列表 |
362
- | isClear | boolean | ❌ | `false` | 是否清除已经不在上下文中的内容(清除项目中不再使用到的源语言键值对),仅仅支持打包模式下使用 |
363
- | isClearSpace | boolean | ❌ | `false` | 是否清除源字符串中左右两边的空格,默认会保留空格 |
364
-
365
- ---
366
-
367
- ## 🔍 deepScan 选项的作用?
368
-
369
- `deepScan` 是一个实验性的属性,用于控制插件是否进行深层扫描字符串。
370
- 默认情况下,插件会扫描字符串或者模版字符串,只需要里面存在一个目标语言就会被扫进去,比如:
371
-
372
- ```js
373
- ;`<div>
374
- <p>你好</p>
375
- </div>`
376
- ```
377
-
378
- 因为里面有一个中文,所以整个字符串会被扫进去,可能会导致翻译不准确,因为我们只想翻译`你好`这个字符串,所以我们可以设置`deepScan`为`true`,插件会对字符串进行切割,重新拼接成模版字符串,值对符合的字符串进行翻译,比如:
379
-
380
- ```js
381
- ;`<div>
382
- <p>${$t('你好')}</p>
383
- </div>`
384
- ```
385
-
386
- 这样就只会翻译`你好`这个字符串,而不会翻译整个字符串。
387
-
388
- ---
389
-
390
- ## 👋 translateType 选项的作用
391
-
392
- `translateType` 是 v1.0.11 新增的属性,有两个可选值`full-auto` 和 `semi-auto` 。
393
-
394
- `full-auto` 第一个是全自动翻译,默认来源语言只支持`中日韩俄`四种语言。
395
-
396
- `semi-auto` 第二个半自动翻译,支持所有来源语言。
397
-
398
- 使用 `semi-auto` 时,用户需要主动去使用`translateKey`对目标字符进行包裹,比如 \$t('hello'),插件会自动完成翻译。
399
-
400
- 例子:
401
-
402
- ```js
403
- const HelloWorld: React.FC<HelloWorldProps> = ({ name = 'World' }) => {
404
- return (
405
- <div className="hello-world">
406
- <h1>
407
- {$t('Hello,')} {name}!
408
- </h1>
409
- <p>{$t('Welcome to our application')}</p>
410
- </div>
411
- )
412
- }
413
-
414
- ```
415
-
416
- ---
417
-
418
- ## ❓ 为什么需要 `buildToDist`?
419
-
420
- 在 Vite 环境中,插件执行后仅会生成翻译配置文件。如果直接构建,虽然翻译配置文件已生成,但默认不会立即将之打包到主包中。⚠️ 因此提供了 `buildToDist` 选项,可在构建时主动将翻译文件打包到主包中。但需要注意,这可能导致您的项目中生成两份翻译配置文件。
421
-
422
- ---
423
-
424
- ## 🔄 如何更新翻译?
425
-
426
- 完成插件运行后,`\lang` 目录会生成两个文件:`index.js` 和 `index.json`。
427
-
428
- - **index.js**:存储翻译相关的函数逻辑。
429
- - **index.json**:存储翻译文本内容。
430
-
431
- 如果需要更新翻译内容,可以直接修改 `index.json` 文件内容。
432
-
433
- ---
434
-
435
- ## ⚠️ 使用注意事项
436
-
437
- 1. **代理要求**
438
-
439
- - 国内使用,强烈推荐使用**有道翻译**
440
- - 使用谷歌翻译的功能时,国内用户必须配置代理环境。
441
- - 默认代理端口为 **7890**。
442
- - 可通过 `proxyOption` 参数自定义代理端口。
443
-
444
- 2. **翻译频率**
445
-
446
- - 谷歌翻译是免费服务,但频繁请求可能触发使用限制 🔒。
447
- - 建议设置一个适当的时间间隔再发起新的翻译请求 💡。
448
-
449
- 3. **翻译更新机制**
450
-
451
- - `globalPath` 目录中的 `index.json` 是核心翻译文件。
452
- - 修改并保存后,您的翻译内容将立即更新。
453
-
454
- ---
455
-
456
- ## 📦 用户群
457
-
458
- 微信群
459
-
460
- ![wx](./wx.jpg)
461
-
462
- ---
463
-
464
- ## 📦 示例项目
465
-
466
- ☁️ 示例项目参考仓库:[example](./example)(点击查看)
467
-
468
- ## 📜 许可证
469
-
470
- 本插件基于 **MIT License** 开源协议 🪪。自由使用,欢迎贡献!
471
-
472
- 希望它能让您的国际化开发变得更加简单和高效!🌍✨
473
-
474
- ---
475
-
476
- ## ✨ 更新
477
-
478
- 自 1.0.5 版本起,用户只需在入口文件中引入插件生成文件夹下的 `index.js` 文件,无需再手动构建语言切换函数文件。👏
479
-
480
- ---
481
-
482
- ## 🎆 作者
483
-
484
- 原始作者:wenps、xu-code、Caleb-Xu、Winfans
485
-
486
- ## 更新日志
487
-
488
- ### v1.1.8 (推荐版本)
489
-
490
- - 是否支持清除前后空格配置重命名
491
-
492
- ### v1.1.7 (推荐版本)
493
-
494
- - enable 能力兼容 翻译初始化补全
495
- - 新增扫描是否支持清除前后空格配置
496
- - 修复异常触发新增翻译问题
497
- - 修复清理配置异常不生效问题
498
-
499
- ### v1.1.6 (推荐版本)
500
-
501
- - 修复模板字符串前后空格清空导致 JSON 对应不上翻译函数的问题
502
- - 修复插值中文括号导致插值失效的问题
503
- - 新增清理配置功能
504
-
505
- ### v1.1.5 (推荐版本)
506
-
507
- - 支持插值翻译
508
-
509
- ### v1.1.4 (推荐版本)
510
-
511
- - 修复排除函数处理模版字符串异常问题
512
- - 谷歌新增interval配置
513
- - 新增翻译器支持自定义接口入参
514
-
515
- ### v1.1.3 (推荐版本)
516
-
517
- - 新增无刷更新语言能力及最佳实践
518
-
519
- ### v1.1.2
520
-
521
- - 修复ai翻译异常
522
-
523
- ### v1.1.1
524
-
525
- - 新增翻译禁用功能
526
-
527
- ### v1.1.0
528
-
529
- - 新增ai翻译器
530
- - 新增翻译插件vue2拓展插件机制
531
-
532
- ### v1.0.26 (推荐版本)
533
-
534
- - 新增自定义拓展名数组
535
-
536
- ### v1.0.25 (推荐版本)
537
-
538
- - 新增通用翻译key
539
-
540
- ### v1.0.24 (推荐版本)
541
-
542
- - 修复半自动模式异常问题
543
-
544
- ### v1.0.23 (推荐版本)
545
-
546
- - 修复打包写入重大bug
547
-
548
- ### v1.0.22
549
-
550
- - 新增扫描翻译器
551
-
552
- ### v1.0.21
553
-
554
- - 新增深度扫描
555
-
556
- ### v1.0.20
557
-
558
- - 修复过滤函数异常问题,以及补充是否覆盖生成配置文件项
559
-
560
- ### v1.0.19
561
-
562
- - 配置文件兼容旧版本
563
-
564
- ### v1.0.18
565
-
566
- - 修复了低版本 Node 中可选链操作导致运行时异常的问题。
567
-
568
- ### v1.0.17
569
-
570
- - 支持基本的服务器端渲染(实验性)
571
-
572
- ### v1.0.16
573
-
574
- - 修复已知问题(vue3注释节点)
575
-
576
- ### v1.0.15
577
-
578
- - 新增百度翻译
579
-
580
- ### v1.0.14
581
-
582
- - 修复新增语言类型,不主动切割问题
583
- - 自动翻译能力新增日语,韩语,俄语
584
-
585
- ### v1.0.13
586
-
587
- - 已知问题修复
588
-
589
- ### v1.0.12
590
-
591
- - 优化类型
592
-
593
- ### v1.0.11
594
-
595
- - 修复已知缺陷
596
- - 新增翻译状态选项,支持半自动状态
597
-
598
- ```js
599
- // 用户可以用 translateKey 包裹需要翻译的文案
600
- // 如:$t('hello'),插件会扫描这些文案并实现自动翻译
601
-
602
- $t('hello')
603
- ```