auto-i18n-plugin-core 1.1.1 → 1.1.3-beta1

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