-
Notifications
You must be signed in to change notification settings - Fork 2
English Document
Use the package to help you do internationalization in an automated manner, automatically collecting entries for specified languages, replacing code with specified internationalization conversion functions, automatic translation, and more.
Note that the tool converts code during compilation, rather than permanently replacing it, which is not destructive
The package is divided into two main parts
- loader. This is a custom
webpack
loader that needs to be specified to be imported to complete the main function of automatically collecting and replacing code. - plugin. This is a custom
webpack
plugin that is needed to complete the function of generating term profiles.
The method used is that 'webpack' uses loader and plugin.
Note that the tool does not include internationalized conversion functions. Each project uses a different language framework and uses a different method of calling the conversion function. The tool is to be used with the internationalization conversion function. If your project is
vue
, you can usevue-i18n
,react
usesreact-intl
andreact-i18next
,angular
usesngx-translate
, or implement your own conversion function, etc. 'i18n-auto-webpack' only provides the ability to include entries, replace code with a specified internationalized conversion function, and translate entries (unless you want to use these capabilities separately).
Here said conversion function, such as
vue-i18n
's$t
method
npm i i18n-auto-webpack
Create a global configuration file i18nauto.config.js
in the project root directory
const {resolve} = require('path')
const rootPath = process.cwd()
module.exports = {
entry: {
filename: 'zh.json', // File name (excluding directory path)
path: resolve(rootPath, './lang') // Absolute directory where the file is located (without file name)
},
translate: {
on: true, // Whether to enable translation
lang: ['en'], // Which languages to translate into
path: resolve(rootPath, './lang'), // The directory where the generated translation file resides
secretId: 'your secretId', // Required. Translate api required by your user information secretId
secretKey: 'your secretKey' // Required. Translate api information required by your user secretKey
}
}
entry
specifies that the collected entries are updated based on the existing Chinese entry configuration table, or created directly if there is none.
For example, if you already have a Chinese term profile in your project, or you have already generated a profile using this tool, the next development needs to update the new or deleted terms based on the existing file.
By default, the collection is also updated to the file in the path specified by entry
. This file is used both as the basis for collecting terms and as the resulting configuration file. If the specified path file does not exist, it is automatically created.
In special cases, if you need to generate a configuration file somewhere other than
entry
, you can specify theoutput
field, which defaults toentry
or you can specify it yourself. However, it is worth noting that when you specify a value different fromentry
, if the files ofentry
andoutput
do not remain the same, each collection of entries will treat any more entries inoutput
thanentry
as new entries, triggering the configuration file to be regenerated. So when you do choose to specifyoutput
, keep manually synchronizing updates to theentry
file (unless of course you have other purposes that need to be distinguished). So my advice is to use just oneentry
field, if there are any special cases
i18nauto.config.js
See more configuration rules i18nauto.config.js
translate
Please refer to the translation Settings section for more instructions Transalte Setting
Do the following in the webpack configuration
exports.export = {
module: {
rules: [
{
test: /\.js$/,
loader: 'i18n-auto-webpack/loader',
options: {
watch: true,
name: 'i18n.t',
dependency: {
name: 'i18n',
value: 'src/common/i18n.js'
}
}
}
]
}
}
To include the language in any file, use the loader of the tool for these files, the loader path referenced is i18n-auto-webpack/loader
.
Common configuration based on the options
option in the example:
Whether to listen for updates. If true
is set, the developer will collect the new term replacement code in the code every time the hot update is triggered. If it is set to false
, only the file that starts the project construction for the first time will collect the entry replacement code, and the newly added entries in subsequent development will not be replaced by the code. Default value is false
。 Multiple loaders
can be used for different watches
.
The call path of the internationalization language switch function. For example, if you want to replace the term entry in the code as the international language switch function, how to call this function will pass what, such as i18n.t('001')
, although the final execution is t
function, but you call this t
need to pass i18n
this object, then the complete call path is i18n.t
, So name passes i18n.t
.
The dependencies required to internationalize the language switching function. For example, the contents of the i18n
object are encapsulated in the src/common/i18n.js
file. To switch, you need to use the t
function in the i18n
object. There are two ways to write dependency
:
// usage 1
options: {
name: 'i18n.t',
dependency: {
name: 'i18n',
value: 'src/common/i18n.js'
}
}
// This will eventually generate code: import i18n from 'src/common/i18n.js'
// The code will then switch languages using `i18n.t()`
// usage 2
options: {
name: 't'
dependency: {
name: 't',
objectPattern: true, // deconstructive
value: 'src/common/i18n.js'
}
}
// This will eventually generate code: import { t } from 'src/common/i18n.js'
// The code will then switch languages using `t()`
For details about loader
configuration, see Loader Feature
i18n-auto-webpack/loader
expects to receive Javascript
content, it works by parsing the code that is passed in Javascript
into AST
, Then analyze the AST
to find and extract term and other series of operations, and then return to the Javascript
code.
So when you want to use i18n-auto-webpack/loader
for a file that is not Javascript
content, please use it after another loader
converts it to Javascript
, please make sure that loader
executes in the order.
For example, if you want to include the language entries of template and script in the .vue
file, use i18n-auto-webpack/loader
for the .vue
file.
// webpack config file
const i18nAutoLoaderOptions = {
watch: true,
name: 'i18n.t',
dependency: {
name: 'i18n',
value: 'src/common/i18n.js'
}
}
// fpr vue-loader v15
module.exports = {
module: {
rules: [
// This is the original rule for using vue-loader on vue files
{
test: /\.vue$/,
loader: 'vue-loader'
},
// For the template section of the vue file. This should be a new rule, can not be used in the original use of 'vue-loader' rule
{
test: /\.vue$/,
resourceQuery: /type=template/,
enforce: 'post',
loader: 'i18n-auto-webpack/loader',
options: i18nAutoLoaderOptions
},
// The same rules used for js files will also apply to the js code in the script part of the vue file.
{
test: /\.js$/,
use: [
{
loader: 'i18n-auto-webpack/loader',
options: i18nAutoLoaderOptions
},
{
loader: 'babel-loader'
}
]
}
]
}
}
In theory, i18n-auto-webpack/loader
can be used with any front-end framework or language, as long as the appropriate loader converts it to Javascript.
Do the following in the webpack configuration
import i18nAutoPlugin from 'i18n-auto-webpack/plugin'
module.exports = {
plugins: [
new i18nAutoPlugin({
watch: true
})
]
}
Whether to monitor updates. If 'true' is set, the developer will collect the newly added Chinese terms in the code and update them into the configuration file every time the hot update is triggered by the code. If the value is set to 'false', only the file that starts the project construction for the first time is used to create a configuration file for entries. The newly added files in subsequent development will not be updated to the configuration file. Default value is false
.
Please refer to more configuration of plugin Plugin Feature
To enable automatic translation function, need to make the appropriate Settings in i18nauto-.config.js
.
const {resolve} = require('path')
const rootPath = process.cwd()
module.exports = {
translate: {
on: true, // Whether to enable translation
lang: ['en'], // Which languages to translate into
path: resolve(rootPath, './lang'), // The directory where the generated translation file resides
secretId: 'your secretId' // Required. Translate api required by your user information secretId
secretKey: 'your secretKey' // Required. Translate api information required by your user secretKey
}
}
The translation api used by this tool is Tencent Translation. As for why I choose Tencent Translation, of course, I have done a variety of translation api research, and finally found that the api of Tencent Translation is relatively more advantageous to use (apart from the translation results, who is more accurate in my English business level is difficult to judge).
When you have a large number of entries that need to be translated, you don't really care if the translation is accurate or not. If you think the individual translation is not correct, you can manually modify the translation in the generated configuration file. No matter which api you use, there will eventually need to be a human calibration.
Due to the adoption of third-party translation apis, all translation apis now require registered users to obtain authorization to invoke, and free users are limited to use. So to use this tool's translation capabilities, users first need to register Tencent Cloud machine translation, obtain 'secretId' and 'secretKey' in the configuration file.
For security reasons, when your project code is public, do not write your or your company's account 'secretId' and 'secretKey' directly into 'i18Nauto-config.js'. Instead, use environment variables to read the environment variables on your local machine. Or set the 'i18Nauto-config. js' file in '.gitignore' for git version control ignore. This way there is no risk of someone stealing your account.
First access Tencent cloud console,Register and log in.
Enter the user-User list and find the corresponding user (if no, create a new user).
Click to enter user details and select Enter API key navigation
Tencent machine translation api has two limitations that we need to pay attention to:
- Text translation is free for 5 million characters a month.
- Request the api no more than five times in one second.
To make it easier for users to use the tool, I have provided two configuration items to stop calling the translation api when the translation exceeds the character limit you specify. see startTotal and endTotal
Note that this number is based on the number of languages translated. For example, if you want to translate "hello" into English and German, then 3 * 2 = 5, which uses up the limit of 5 characters. 3 is the number of characters in Chinese, and 2 is translated into two languages.
The second restriction, 'i18n-auto-webpack', is implemented internally by the tool to satisfy this condition. But because of this, let's say your coded IDE is set to autosave, and when you type the code while autosave triggers recompilation, it will trigger the inclusion of Chinese entries, included in the new Chinese entries will trigger translation, if you save a lot of times quickly, it will frequently trigger the translation interface, And 'i18n-auto-webpack' because of the throttling process, it may lead to less real-time translation, which is inevitable. And we can type the code incorrectly or change it back and forth, the more translations triggered, the more characters translated, and the free limit is only 5 million characters.
Therefore, for these two constraints, to enable automatic translation function, my recommendation is
- Either your coded IDE is set to manually save to reduce frequent triggering of hot updates; (Best practice)
- Or the loader and plugin part of the 'watch' configuration set to 'false', do not monitor changes and update;
- Or turn Auto translation off and select the 'i18n-auto-webpack' method, which provides a separate translation capability, 'i18n-auto-webpack/translate', and write a command that manually triggers the translation whenever you want it. (Best bet)
For details on using separate translation capabilities, see belowTranslate Function
Using the ability provided by 'i18n-auto-webpack/translate', you can write a script to achieve the translation capability.
This allows you to rely on it to write a 'nodejs' script and then write a command in' npm script 'specifically to run the command for final unified translation after the developer has basically written the code. This allows automatic translation to be turned off, circumventing some of the problems caused by the conditional translation api(See the previous section "Limitations of the translation api")
Or if you have already done the internationalization plan, you have already implemented the code replacement and inclusion of Chinese, the only thing left is the translation work, not yet generated the translation language configuration file, then you can use 'i18n-auto-webpack/translate' to help you complete this step.
If you want to use this translation capability alone, you still need to use it with the 'i18Nauto-config. js' file, you need to set the translation interface required by your' secretId 'and' secretKey '
const { createTranslate } = require('i18n-auto-webpack/translate')
const path = require('path')
const target = {
path: path.resolve(__dirname), // The directory in which the translation results are placed
lang: ['en'] // The language to be translated
}
const source = {
path: path.resolve(__dirname, 'zh.json') // Which Chinese configuration file is used to generate the corresponding internationalization language configuration file
}
// After this method is executed, the translation result is automatically created/modified to the specified directory
createTranslate(target, source)
There are three params, in the following order target
, source
, needFile
<Obejct>target
:
Param name | Type | Desc | Default | Required |
---|---|---|---|---|
path | String | The directory absolute path to the translation file, excluding the file name | Run the method's path + lang directory, which is automatically created if it is not | No |
lang | Array | Translation language list | ['en'] | No |
nameRule | Function | Format the name of the translation file | lang + '.json' | No |
<Obejct>source
:
Param name | Type | Desc | Default | Required |
---|---|---|---|---|
path | String | The directory absolute path to the translation source file, containing the file name | - | Yes |
needFile
:
Booealn
. Default is true
。
Represents whether the translation result needs to be generated into the specified directory
- If a file with the same name exists, the system determines which Chinese characters need to be translated based on the contents of the existing file, and then merges the translation results into the file.
- If there is no file with the same name, all Chinese translations will be created directly.
Promise
. The result of the callback returned is an object with the translated language as' key 'and the translated result as' value', as in
en: {
1: 'hello',
2: 'Who am i'
}
When certain terms in the code do not need to be internationalized, then you can add a block comment in the form of a line before the term, indicating that the term does not need to be internationalized, such as:
const word = /*no-i18n-auto*/ '你好';
new Error(/*no-i18n-auto*/ '报错了');
When you have to use internationalized conversion functions directly in your code, you can still use them with confidence. Such as
// i18n.tc is an internationalized transition function
const word = i18n.tc('1')
The corresponding entry is
// zh.json
{
"1": "你好"
}
i18n-auto-webpack
will automatically determine whether the method you call is an internationalization conversion function according to the 'name' value of the internationalization conversion dependency set by you in 'loader', if yes, the term table will reserve the corresponding term for you, and will not say that because the code does not have this Chinese, The corresponding term is deleted from the term table. Of course, at this time you need to manually set the corresponding term in the term table.
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: 'i18n-auto-webpack/loader',
options: {
watch: true,
name: 'i18n.tc', // That's the name to judge
dependency: {
name: 'i18n',
value: 'src/common/i18n.js'
}
}
}
]
}
]
}
}
This scenario is more yes, you need to use the internationalization conversion function to pass richer parameters to complete richer capabilities, or the string with 'html' tag needs to be directly rendered (like 'vue' 'v-html'), if you do not handle it yourself to write the internationalization conversion function form, Then the 'html' tag will also be extracted and translated as part of the entry, which may break your logic.
If you use an internationalized conversion function that is called not only by name but also by other means, and you want to keep the entry for the corresponding key, then you can use the alias configuration to specify other ways to call it. For example, if you use 'vue-i18n ', you can use' this.$t() 'directly in the component to call the conversion, you can set' alias: ['$t', '_vm.$t'] 'to preserve the key that calls it:
{
loader: 'i18n-auto-webpack/loader',
options: {
watch: true,
name: 'i18n.tc',
alias: ['$t', '_vm.$t'],
dependency: {
name: 'i18n',
value: 'src/common/i18n.js'
}
}
}
At this point, the code uses' i18n.tc 'and' $t 'methods in the key corresponding terms are retained.
In addition,
The use of 'i18n-auto-webpack' is a tool to improve work efficiency, and can be relatively successful in finding Chinese entries in the code to replace, but a variety of code written by various developers, there will be various possibilities, I can only say that most of the general scenes are included, if you encounter special writing or scenes, Unable to successfully extract Chinese using this tool, please let me know and I will supplement, or you may need to adjust the writing of the internationalized conversion function directly in the code. It is inevitable that there is a scenario in the project code that directly uses the internationalization conversion function + Chinese (' i18n-auto-webpack 'helps to include internationalization)。
Feature | Desc | Type | Required | Default |
---|---|---|---|---|
entry |
Entry file configuration for the entry configuration table. When compiling translation code, you need to know the key values of the entries in the existing configuration table, so you need to specify a configuration table file first. Note that this file is a configuration table for the language you want to collect, not a translated configuration table for another language,Has the following properties: | Object | Yes | |
path :Path of the configuration table file (excluding the file name) |
String | No | Project root directory/lang | |
filename :The name of the configuration table file (excluding the path) |
String | No | zh.json | |
output |
Generate the entry configuration table file information included in the code, Has the following properties: | Object | No | When 'entry' is set and 'output' is not set, then follow the 'entry' setting |
path :Path of the configuration table file (excluding the file name) |
String | No | Project root directory/lang | |
filename :The name of the configuration table file (excluding the path) |
String | No | zh.json | |
localePattern |
Included language regular expression, the default is to include Chinese. So if you want to include other languages, you can pass in regular expressions that actually represent other languages | RegExp | No | /[\u4e00-\u9fa5]/ |
translate |
Set up automatic translation related, Has the following properties: | Object | No | false,Do not enable automatic translation |
on :Whether to enable translation |
Boolean | No | false | |
lang :Which languages to translate into |
Array | No | ['en']。The language identification can be referred toapi | |
path : directory where the generated translation file resides |
String | No | Project root directory/lang | |
nameRule :The generated translation file name |
Function | No | nameRule (lang) {return lang + '.json' } | |
startTotal :Indicates how many character limit you have used. The number of translated characters triggered by this startup service will be calculated based on this limit |
Number | No | 0 | |
endTotal :When the specified endTotal limit is reached, no more translation requests are triggered. The default value is Tencent translation api free quota, do not want to limit transmission Infinity
|
Number | No | 5000000 | |
secretId :Translate api user identity secretId, please go to Tencent cloud console to check |
String | Yes | ||
secretKey :Translate api user identity secretKey, please go to Tencent cloud console to check |
String | Yes | ||
region :The language of which region is translated |
String | No | ap-beijing | |
endpoint :Interface request address |
String | No | tmt.tencentcloudapi.com | |
source :The language to be translated |
String | No | zh | |
projectId :You can enter the project ID according to the configuration in Console, Account Center, and Project Management. If there is no configuration, enter the default project ID:0 |
Number | No | 0 |
About startTotal
and endTotal
Because the Tencent Translation api has a free translation limit of 5 million characters per month, if you exceed that, you have to pay. So the 'startTotal' and 'endTotal' Settings will make you feel more comfortable using them. Note that 'startTotal' only accumulates on it from the start of the service (if dev-server is started). We don't know how much credit you used for the previous service, so you may need to change this' startTotal 'every time you start the service
Unfortunately, Tencent machine translation api has no api to query the user's usage limit
As for the sub-attributes under 'translate', starting from 'secretId', they are all configured according to the requirements of Tencent Cloud translation api. For more information, please visit 腾讯云翻译api文档
Feature | Desc | Type | Required | Default |
---|---|---|---|---|
includes |
For files (folders) that support internationalization, the element value is the absolute path of the file (folder). If it is the folder address, end with '/'. Then all files in the folder will be internationalized. Can be used with excludes , excludes has higher priority. |
Array | No | [] |
excludes |
The element value is the absolute path to the file (folder). If it is the folder address, end with '/', then all files in the folder are excluded. Can be used with includes , excludes has higher priority. |
Array | No | [] |
dependency |
This configuration can be used if you need to introduce certain dependencies into the file when translating code needed for internationalization. Has the following properties: | Object | No | |
name :The name of the variable assigned by the imported dependency, like import name from 'xxx'
|
String | Mandatory if dependency is set | ||
value :The path of the dependency introduced, which can be in any format, is actually a string, just like the path of the 'import' or 'require' methods that you want to write in your code. Note that this value is used to determine whether the dependency has been imported into the document. The judgment is based on the exact match of the path string, rather than the actual import file. The import path of a file is not the same, which will cause incorrect judgment |
String | Mandatory if dependency is set | ||
objectPattern :Introduced forms of dependency. If it is in deconstructed format, it needs to be set to true. |
Boolean | No | ||
name |
Replace the full pathname of the function call that internationalizes the entry in the code | String | Yes | |
alias |
An alias for the full pathname of the function call that internationalizes the entry in the replacement code | Array | No | |
watch |
Whether to monitor file changes in real time and update keys in the configuration table in real time | Boolean | No | false |
transform |
Whether the code needs to be converted. Set this to false if you only want to include entries in your project without converting the code | Boolean | No | true |
Configuration item | Description | Type | Required | Default |
---|---|---|---|---|
output |
The priority of the generated configuration table file is higher than that of the global configuration file i18nauto-config.js,Has the following properties: | Object | No | |
path :Path of the configuration table file (excluding the file name) |
String | No | ||
filename :The name of the configuration table file (excluding the path) |
String | No | ||
watch |
Whether to monitor file changes in real time and update configuration files in real time. This is mainly after the development environment is started. When 'watch' is' Object ', it has the following properties: | Object | Boolean | No | false |
on :Whether to enable listening |
Boolean | No | false | |
sourceMap |
Whether to generate a mapping table. When 'sourceMap' is' Object ', it has the following properties: | Object | Boolean | No | false |
on :Whether to generate an entry mapping table, recording which entries are in which file |
Boolean | No | false | |
path :Path for storing the generated mapping file (excluding the file name) |
String | No | Project root directory/lang | |
filename :Generated mapping file name (without path) |
String | No | zh.sourcemap.json |
However, starting a project for the first time, such as in a development environment or a packaged production environment, will necessarily require an update to the entry configuration table depending on the situation.
If you are interested and have any questions when using it, please feel free to ask questions and I will try my best to answer them for you.
If you like it, please give me a star, thanks github