auto-i18n-plugin-core 1.1.9 → 1.1.11

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "auto-i18n-plugin-core",
3
- "version": "1.1.9",
3
+ "version": "1.1.11",
4
4
  "description": "vite, webpack automatic translation plugin core code.",
5
5
  "keywords": [
6
6
  "i18n",
@@ -38,6 +38,7 @@
38
38
  "@vitalets/google-translate-api": "^9.2.0",
39
39
  "axios": "^1.6.8",
40
40
  "crypto-js": "^4.2.0",
41
+ "progress": "^2.0.3",
41
42
  "tunnel": "0.0.6"
42
43
  },
43
44
  "devDependencies": {
@@ -50,6 +51,7 @@
50
51
  "@types/babel__generator": "^7.6.8",
51
52
  "@types/crypto-js": "^4.2.2",
52
53
  "@types/node": "^20.3.3",
54
+ "@types/progress": "^2.0.7",
53
55
  "@types/tunnel": "^0.0.7",
54
56
  "babel-plugin-import": "^1.13.6",
55
57
  "rollup": "^4.3.0",
@@ -58,6 +60,9 @@
58
60
  "rollup-plugin-terser": "^7.0.2",
59
61
  "typescript": "^5.1.6"
60
62
  },
63
+ "volta": {
64
+ "extends": "../../package.json"
65
+ },
61
66
  "scripts": {
62
67
  "build": "rollup -c ./rollup.config.ts --configPlugin typescript"
63
68
  }
package/readme-en.md ADDED
@@ -0,0 +1,633 @@
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, Rsbuild 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
+ ## 🌟 Quick Start 🚀
47
+
48
+ ### 1️⃣ Install Plugin 📦
49
+
50
+ #### **🌐 Vite Project:**
51
+
52
+ ```bash
53
+ npm install vite-auto-i18n-plugin --save-dev
54
+ # or
55
+ yarn add vite-auto-i18n-plugin --dev
56
+ ```
57
+
58
+ #### **🛠️ Webpack Project:**
59
+
60
+ ```bash
61
+ npm install webpack-auto-i18n-plugin --save-dev
62
+ # or
63
+ yarn add webpack-auto-i18n-plugin --dev
64
+ ```
65
+
66
+ #### **⚡ Rsbuild Project:**
67
+
68
+ ```bash
69
+ npm install rsbuild-auto-i18n-plugin --save-dev
70
+ # 或
71
+ yarn add rsbuild-auto-i18n-plugin --dev
72
+ ```
73
+
74
+ ---
75
+
76
+ ### 2️⃣ Language Switching 🌐
77
+
78
+ #### ⚙️ Basic Switching
79
+
80
+ ```js
81
+ window.localStorage.setItem('lang', value)
82
+ window.location.reload()
83
+
84
+ // value is the key of the language mapping object
85
+ // The mapping object is located in the lang/index.js file by default. You can check this part of the code inside.
86
+ const langMap = {
87
+ 'en': (),
88
+ 'zhcn': ()
89
+ }
90
+ ```
91
+
92
+ #### 📲 Instant Language Switching
93
+
94
+ 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.
95
+
96
+ ```js
97
+ window.$changeLang('en')
98
+ ```
99
+
100
+ For example, in Vue2, you can switch languages without refreshing the page in the following way:
101
+
102
+ ```Html
103
+ <template>
104
+ <div id="app" v-if="isShow">
105
+ <button @click="changeLang('en')">Switch to English</button>
106
+ <button @click="changeLang('zh-cn')">Switch to Chinese</button>
107
+ <router-view></router-view>
108
+ </div>
109
+ </template>
110
+ <script>
111
+ export default {
112
+ data() {
113
+ return {
114
+ isShow: true
115
+ }
116
+ },
117
+ methods: {
118
+ changeLang(lang) {
119
+ window.$changeLang(lang)
120
+ this.isShow = false
121
+ this.$nextTick(() => {
122
+ this.isShow = true
123
+ })
124
+ }
125
+ }
126
+ }
127
+ </script>
128
+ ```
129
+
130
+ #### 🔄 Replace Language Packs
131
+
132
+ If you want to modify the built - in generated language packs, you can directly modify the `langMap` in the global object. For example:
133
+
134
+ ```js
135
+ window.langMap = {
136
+ en: {
137
+ zccsau6: 'hello'
138
+ },
139
+ 'zh-cn': {
140
+ zccsau6: '你好'
141
+ }
142
+ }
143
+ ```
144
+
145
+ Then you can refresh the page by using the above **Instant Language Switching** method.
146
+
147
+ ---
148
+
149
+ ### 3️⃣ Basic Configuration 🔧
150
+
151
+ #### **Vite Configuration Example** (vite.config.js):
152
+
153
+ ```javascript
154
+ import vitePluginsAutoI18n, { YoudaoTranslator } from 'vite-auto-i18n-plugin'
155
+ import vue from '@vitejs/plugin-vue'
156
+ import { defineConfig } from 'vite'
157
+
158
+ export default defineConfig({
159
+ plugins: [
160
+ vue({
161
+ template: {
162
+ compilerOptions: {
163
+ hoistStatic: false,
164
+ cacheHandlers: false
165
+ }
166
+ }
167
+ }),
168
+ vitePluginsAutoI18n({
169
+ translator: new YoudaoTranslator({
170
+ appId: '4cdb9baea8066fef',
171
+ appKey: 'ONI6AerZnGRyDqr3w7UM730mPuF8mB3j'
172
+ })
173
+ })
174
+ ]
175
+ })
176
+ ```
177
+
178
+ #### **Webpack Configuration Example** (webpack.config.js):
179
+
180
+ ```javascript
181
+ const webpackPluginsAutoI18n = require('webpack-auto-i18n-plugin')
182
+ const { YoudaoTranslator } = require('webpack-auto-i18n-plugin')
183
+
184
+ const i18nPlugin = new webpackPluginsAutoI18n.default({
185
+ translator: new YoudaoTranslator({
186
+ appId: '4cdb9baea8066fef',
187
+ appKey: 'ONI6AerZnGRyDqr3w7UM730mPuF8mB3j'
188
+ })
189
+ })
190
+
191
+ module.exports = {
192
+ plugins: [
193
+ new VueLoaderPlugin(),
194
+ new HtmlWebpackPlugin({
195
+ template: './public/index.html'
196
+ }),
197
+ i18nPlugin
198
+ ]
199
+ }
200
+ ```
201
+
202
+ #### **Rsbuild Configuration Example** (rsbuild.config.js):
203
+
204
+ ````javascript
205
+ const rsbuildPluginsAutoI18n = require('rsbuild-auto-i18n-plugin')
206
+ const { YoudaoTranslator } = require('rsbuild-auto-i18n-plugin')
207
+
208
+ export default defineConfig({
209
+ plugins: [
210
+ pluginReact(),
211
+ rsbuildPluginsAutoI18n({
212
+ targetLangList: ['en'],
213
+ translator: new YoudaoTranslator({
214
+ appId: '4cdb9baea8066fef',
215
+ appKey: 'ONI6AerZnGRyDqr3w7UM730mPuF8mB3j'
216
+ })
217
+ })
218
+ ],
219
+ });
220
+
221
+ ---
222
+
223
+ ### 4️⃣ Translator Configuration Examples 🛠️
224
+
225
+ 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.
226
+
227
+ The following examples use `vite` as an example, and `webpack`、`rsbuild` is similar.
228
+
229
+ #### **Using Google Translate (Default)**
230
+
231
+ ```javascript
232
+ import { GoogleTranslator } from 'vite-auto-i18n-plugin'
233
+
234
+ ...
235
+ translator: new GoogleTranslator({
236
+ proxyOption: {
237
+ host: '127.0.0.1',
238
+ port: 7890,
239
+ headers: {
240
+ 'User-Agent': 'Node'
241
+ }
242
+ }
243
+ })
244
+ ...
245
+ ````
246
+
247
+ #### **Using Youdao Translation**
248
+
249
+ You need to apply for an API. [API documentation](https://ai.youdao.com/DOCSIRMA/html/trans/api/wbfy/index.html).
250
+
251
+ ```javascript
252
+ import { YoudaoTranslator } from 'vite-auto-i18n-plugin'
253
+
254
+ ...
255
+ translator: new YoudaoTranslator({
256
+ appId: 'The appId you applied for',
257
+ appKey: 'The appKey you applied for'
258
+ })
259
+ ...
260
+ ```
261
+
262
+ #### **Baidu Translator**
263
+
264
+ You need to apply for an API. [API documentation](https://api.fanyi.baidu.com/product/113).
265
+
266
+ ```javascript
267
+ import { BaiduTranslator } from 'vite-auto-i18n-plugin'
268
+
269
+ ...
270
+ translator: new BaiduTranslator({
271
+ appId: 'The appId you applied for', // Baidu Translate AppId
272
+ appKey: 'The appKey you applied for' // Baidu Translate AppKey
273
+ })
274
+ ...
275
+ ```
276
+
277
+ #### **Volcengine AI Translator**
278
+
279
+ 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.
280
+ Introduction to Volcengine large models: https://www.volcengine.com/docs/82379/1099455.
281
+ You need to activate the large model service and apply for an API. [API documentation](https://www.volcengine.com/docs/82379/1298454).
282
+
283
+ ```javascript
284
+ import { VolcengineTranslator } from 'vite-auto-i18n-plugin'
285
+
286
+ ...
287
+ translator: new VolcengineTranslator({
288
+ apiKey: 'The apiKey you applied for',
289
+ 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.'
290
+ })
291
+ ...
292
+ ```
293
+
294
+ #### **Empty Translator**
295
+
296
+ If you only need to scan the target language without performing translation, this translator will generate a JSON file.
297
+
298
+ ```javascript
299
+ import { EmptyTranslator } from 'vite-auto-i18n-plugin'
300
+
301
+ ...
302
+ translator: new EmptyTranslator()
303
+ ...
304
+ ```
305
+
306
+ #### **Custom Translator**
307
+
308
+ If you have a personal translation API, you can customize a translator in the following ways:
309
+
310
+ The simplest way is to define a translator instance using the `Translator` base class.
311
+
312
+ ```javascript
313
+ import { Translator } from 'vite-auto-i18n-plugin'
314
+ import axios from 'axios'
315
+
316
+ ...
317
+ translator: new Translator({
318
+ name: 'My Translator',
319
+ // Translation method
320
+ fetchMethod: (str, fromKey, toKey, _separator) => {
321
+ // 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
322
+ const myApi = 'https://www.my-i18n.cn/api/translate?from=${fromKey}&to=${toKey}&t={+new Date}'
323
+ return axios.post(myApi, { str })
324
+ .then(res => res.data)
325
+ },
326
+ // Interface trigger interval. Some interfaces may be blocked if triggered frequently. Please set a reasonable interface trigger interval according to the actual situation.
327
+ interval: 1000
328
+ })
329
+ ...
330
+ ```
331
+
332
+ If you need more advanced features, you can use inheritance. However, there is currently no relevant scenario.
333
+
334
+ ```javascript
335
+ import { Translator } from 'vite-auto-i18n-plugin'
336
+
337
+ class CustomTranslator extends Translator {
338
+ constructor () {
339
+ super({
340
+ name: 'My Translator',
341
+ ...
342
+ })
343
+ }
344
+ }
345
+
346
+ ...
347
+ translator: new CustomTranslator()
348
+ ...
349
+ ```
350
+
351
+ ---
352
+
353
+ ### 5️⃣ Project Entry Configuration 🏗️
354
+
355
+ Please import the language configuration file at the top of the **project entry file** (e.g., `main.js`):
356
+
357
+ ```javascript
358
+ 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.
359
+ ```
360
+
361
+ ---
362
+
363
+ ## ⚙️ Configuration Parameters
364
+
365
+ | Parameter | Type | Required | Default | Description |
366
+ | -------------------- | ---------- | -------- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
367
+ | enabled | boolean | ❌ | `true` | Whether to trigger translation. |
368
+ | translateType | string | ❌ | `full-auto` | Translation mode: `full-auto` or `semi-auto` |
369
+ | translateKey | string | ✅ | `$t` | Translation function name (e.g., `$t`) |
370
+ | excludedCall | string[] | ❌ | `['$i8n', 'require', …]` | Function calls to exclude from translation |
371
+ | excludedPattern | RegExp[] | ❌ | `[/\.\w+$/]` | Patterns to exclude (e.g., file extensions) |
372
+ | excludedPath | string[] | ❌ | `['node_modules']` | Directories to exclude (e.g., `node_modules`) |
373
+ | includePath | RegExp[] | ❌ | `[/src\//]` | Whitelist of directories to include (default: `src`) |
374
+ | globalPath | string | ❌ | `'./lang'` | Path for translation config files |
375
+ | distPath | string | ✅ | `''` | Output path for built files |
376
+ | distKey | string | ✅ | `'index'` | Main translation file name |
377
+ | namespace | string | ✅ | `lang` | Project namespace for distinguishing translation configs |
378
+ | originLang | string | ✅ | `'zh-cn'` | Source language |
379
+ | targetLangList | string[] | ✅ | `['en']` | Target languages |
380
+ | buildToDist | boolean | ❌ | `false` | Whether to bundle translation files into main build |
381
+ | translator | Translator | ❌ | `GoogleTranslator` | Translator instance |
382
+ | translatorOption | object | ❌ | `{}` | Translator options (lower priority than `translator`) |
383
+ | rewriteConfig | boolean | ❌ | `true` | Whether to rewrite config file on each plugin run |
384
+ | deepScan | boolean | ❌ | `false` | Experimental: Whether to perform deep string scanning |
385
+ | commonTranslateKey | string | ❌ | `''` | General translation key |
386
+ | insertFileExtensions | string[] | ❌ | `[]` | List of file extensions to insert translation code into |
387
+ | isClear | boolean | ❌ | `false` | Whether to clear content not in context (clear source language key-value pairs not in context), only supported in build mode |
388
+ | isClearSpace | boolean | ❌ | `false` | Whether to remove whitespace from both ends of source strings, whitespace is preserved by default |
389
+
390
+ ---
391
+
392
+ ## 🔍 What does `deepScan` do?
393
+
394
+ `deepScan` is an experimental property controlling whether the plugin performs deep string scanning.
395
+
396
+ By default, the plugin scans strings/template strings - if any target language text is found, the entire string is included:
397
+
398
+ ```js
399
+ ;`<div>
400
+ <p>你好</p>
401
+ </div>`
402
+ ```
403
+
404
+ 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:
405
+
406
+ ```js
407
+ ;`<div>
408
+ <p>${$t('你好')}</p>
409
+ </div>`
410
+ ```
411
+
412
+ Now only '你好' gets translated, not the entire string.
413
+
414
+ ---
415
+
416
+ ## 👋 `translateType` Functionality
417
+
418
+ Added in v1.0.11, with two options:
419
+
420
+ `full-auto`: Fully automatic translation (default supports Chinese, Japanese, Korean, Russian)
421
+
422
+ `semi-auto`: Semi-automatic translation (supports all source languages)
423
+
424
+ In `semi-auto` mode, users must wrap target text with `translateKey` (e.g., `$t('hello')`), which the plugin will then translate.
425
+
426
+ Example:
427
+
428
+ ```js
429
+ const HelloWorld: React.FC<HelloWorldProps> = ({ name = 'World' }) => {
430
+ return (
431
+ <div className="hello-world">
432
+ <h1>
433
+ {$t('Hello,')} {name}!
434
+ </h1>
435
+ <p>{$t('Welcome to our application')}</p>
436
+ </div>
437
+ )
438
+ }
439
+ ```
440
+
441
+ ---
442
+
443
+ ## ❓ Why `buildToDist`?
444
+
445
+ 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.
446
+
447
+ ---
448
+
449
+ ## 🔄 How to Update Translations?
450
+
451
+ After running the plugin, two files are generated in `\lang`:
452
+
453
+ - **index.js**: Translation function logic
454
+ - **index.json**: Translation content
455
+
456
+ To update translations, simply modify `index.json`.
457
+
458
+ ---
459
+
460
+ ## ⚠️ Usage Notes
461
+
462
+ 1. **Proxy Requirements**
463
+
464
+ - In China, **Youdao Translate** is strongly recommended
465
+ - Google Translate requires proxy configuration
466
+ - Default proxy port: **7890** (customizable via `proxyOption`)
467
+
468
+ 2. **Translation Frequency**
469
+
470
+ - Google Translate is free but may limit frequent requests 🔒
471
+ - Set reasonable intervals between requests 💡
472
+
473
+ 3. **Translation Updates**
474
+ - `index.json` in `globalPath` is the core translation file
475
+ - Changes take effect immediately after saving
476
+
477
+ ---
478
+
479
+ ## 📦 User Group
480
+
481
+ QQ Group
482
+
483
+ ![qq](./qq.jpg)
484
+
485
+ ---
486
+
487
+ ## 📦 Example Project
488
+
489
+ Example project: [example](./example) (click to view)
490
+
491
+ ## 📜 License
492
+
493
+ MIT License 🪪 - Free to use and contribute!
494
+
495
+ May this plugin make your i18n development easier and more efficient! 🌍✨
496
+
497
+ ---
498
+
499
+ ## ✨ Update
500
+
501
+ Since v1.0.5, simply import the generated `index.js` in your entry file - no need to manually create language switching functions. 👏
502
+
503
+ ---
504
+
505
+ ## 🎆 Authors
506
+
507
+ Original authors: wenps, xu-code, Caleb-Xu, Winfans
508
+
509
+ ### v1.1.10 (Recommended Version)
510
+
511
+ - Added rsbuild plugin
512
+
513
+ ## Changelog
514
+
515
+ ### v1.1.9 (Recommended Version)
516
+
517
+ - Fixed issue where deepScan string splitting wasn't handling line breaks and other special characters
518
+
519
+ ### v1.1.8 (Recommended Version)
520
+
521
+ - Renamed configuration for controlling leading/trailing whitespace removal
522
+
523
+ ### v1.1.7 (Recommended Version)
524
+
525
+ - Added compatibility for enable feature and translation initialization completion
526
+ - Added configuration option to control whether to remove leading/trailing whitespace during scanning
527
+ - Fixed issue with abnormal triggering of new translations
528
+ - Fixed issue where cleanup configuration was not taking effect
529
+
530
+ ### v1.1.6 (Recommended Version)
531
+
532
+ - Fixed issue where clearing whitespace before/after template strings caused mismatch between JSON and translation functions
533
+ - Fixed issue where Chinese brackets in interpolation caused interpolation to fail
534
+ - Added configuration cleanup functionality
535
+
536
+ ### v1.1.5 (Recommended Version)
537
+
538
+ - Added support for interpolation translation
539
+
540
+ ### v1.1.4 (Recommended Version)
541
+
542
+ - Fixed template string processing exception in exclude functions
543
+ - Added interval configuration for Google Translate
544
+ - Added support for custom interface parameters in translators
545
+
546
+ ### v1.1.3 (Recommended Version)
547
+
548
+ - Added the ability to update languages without refreshing and best practices
549
+
550
+ ### v1.1.2
551
+
552
+ - Fixed AI translation exceptions
553
+
554
+ ### v1.1.1
555
+
556
+ - New translation disable function
557
+
558
+ ### v1.1.0
559
+
560
+ - New AI translator
561
+ - New Vue2 extension plugin mechanism for translation plugins
562
+
563
+ ### v1.0.26 (Recommended Version)
564
+
565
+ - Added custom extension arrays
566
+
567
+ ### v1.0.25 (Recommended Version)
568
+
569
+ - Added a universal translation key
570
+
571
+ ### v1.0.24 (Recommended Version)
572
+
573
+ - Fixed the exception issue in semi-automatic mode
574
+
575
+ ### v1.0.23 (Recommended Version)
576
+
577
+ - Fixed a major bug in packaging and writing.
578
+
579
+ ### v1.0.22
580
+
581
+ - Added scan translator
582
+
583
+ ### v1.0.21
584
+
585
+ - Added deep scanning
586
+
587
+ ### v1.0.20
588
+
589
+ - Fixed filter function issues and added config overwrite option
590
+
591
+ ### v1.0.19
592
+
593
+ - Backward compatibility for config files
594
+
595
+ ### v1.0.18
596
+
597
+ - Fixed optional chaining issues in older Node versions
598
+
599
+ ### v1.0.17
600
+
601
+ - Basic SSR support (experimental)
602
+
603
+ ### v1.0.16
604
+
605
+ - Fixed Vue3 comment node issues
606
+
607
+ ### v1.0.15
608
+
609
+ - Added Baidu Translate
610
+
611
+ ### v1.0.14
612
+
613
+ - Fixed new language type segmentation
614
+ - Added Japanese, Korean, Russian support
615
+
616
+ ### v1.0.13
617
+
618
+ - Bug fixes
619
+
620
+ ### v1.0.12
621
+
622
+ - Type optimizations
623
+
624
+ ### v1.0.11
625
+
626
+ - Bug fixes
627
+ - Added `translateType` option for semi-auto mode
628
+
629
+ ```js
630
+ // Users can wrap text with translateKey
631
+ // e.g., $t('hello') - plugin will scan and translate these
632
+ $t('hello')
633
+ ```