Write a vscode plug-in to help read the code of I18N project
introduce
The project the author is currently involved in is for global users. The project has to be internationalized, even if it is just a simple projectOK button
ofOK copywriting
It has to be translated into the languages of different countries, so we can’t directly name it in the codeok
Instead, it may be nameduser_base_plan_edit_ok_button
This kind of name, and in order to distinguishi18n
Similar to other naming methods, our team will use all uppercaseUSER_BASE_PLAN_EDIT_OK_BUTTON
, and reading more such code will makeDry eyes
, similar to the pseudo code in the following figure:
To solve this problemBad reading
My expected effect is that when the mouse hovers over the target text, a pop-up box will appear, and the pop-up box should at least tell me the Chinese or English meaning of the word. The effect is as follows:
It can be seen that if this plug-in is done well, it may not only be used ini18n
This is just a point. It can be used in many aspects, such as a code103993283
The specific meaning of this code can be displayed as a plug-in.
1: Initialize vscode project
Students who have not done vscode plug-in are recommended to read the introductory tutorial I wrote first:
- Remember a super detailed sharing meeting of front-end “vscode plug-in writing practice” (recommended Collection) (Part I)
- Remember a super detailed sharing meeting on the front-end “vscode plug-in writing practice” (recommended Collection) (Part 2)
The plug-in I made this time is aimed at my current project and has no extensive application ability, so it was not released to the official vscode. After development, it was packaged and sent to the company’s intranet and group.
Create project: the project name here is tentatively calledi18n2c
yo code
2: Initialize schema
extension.js
Clean up the documents:
const vscode = require("vscode");
function activate(context) {
vscode. window. Showinformationmessage ("I18N translation plug-in loading completed");
}
module.exports = {
activate,
};
Modificationpackage.json
File: set to start loading our plug-ins when the resources are loaded
{
// ...
"activationEvents": [
"onStartupFinished"
],
// ...
}
Clickf5
Start the debugging mode, and the following figure shows that the plug-in can be started normally:
3: Initialize hover file
We puthover
The following logic is placed in SRC:
Make a simple transformationextension.js
, add the hover method:
const vscode = require("vscode");
const hover = require("./src/hover");
function activate(context) {
vscode. window. Showinformationmessage ("I18N translation plug-in loading completed");
context.subscriptions.push(hover);
}
module.exports = {
activate,
};
hover.js
Export handling method when hovering
const vscode = require("vscode");
module.exports = vscode.languages.registerHoverProvider("*", {
provideHover(document, position) {
return new vscode. Hover (` I18N plug-in comes to help you get through the robbery ';
},
});
When you hover in any position, the effect is as follows:
4: Recognition of I18N target copy
The technical schemes of each team are different. Here I only design the scheme of our team, hoping to attract jade by throwing bricks:
Our teamI18N copywriting
Are capitalized and useUnderline
Linked to each other, and I found that the global exceptI18N copywriting
There are no more than three characters in the stringUnderline
, andI18N copywriting
At least fourUnderline
Therefore, at present, I use to judge whether the string contains more than three characters'_'
。
const vscode = require("vscode");
module.exports = vscode.languages.registerHoverProvider("*", {
provideHover(document, position) {
const word = document.getText(document.getWordRangeAtPosition(position));
if (word.split("_").length > 3) {
return new vscode. Hover (` I18N plug-in comes to help you get through the robbery ';
}
},
});
aboveword
That’s what we gotHovered text
5: How to translate into Chinese
We found it up thereTo be translated
Here we will study how to translate this copy. Generally, there will be a translation dictionary package for I18N, one of which is our teamJSON file
, the difference is that each key is lowercase. The general appearance is as follows:
All I have to do is read this file andTo be translated
Convert your copy to lowercase and match it again.
const vscode = require("vscode");
const fs = require("fs");
module.exports = vscode.languages.registerHoverProvider("*", {
provideHover(document, position) {
const word = document.getText(document.getWordRangeAtPosition(position));
let jsonCN = JSON.parse(
fs.readFileSync("/xxxx/xxxxx/langs/zh-CN.json")
);
if (word.split("_").length > 3) {
return new vscode. Hover (` I18N plug-in comes to help you through the robbery:
-Chinese: ${jsoncn [word. Tolocalelovercase()]}
`);
}
},
});
OursI18N dictionary
They are all placed in the same folder, so I only need to know this folder. By default, take out the Chinese and English copy in it and transform it.
const vscode = require("vscode");
const fs = require("fs");
module.exports = vscode.languages.registerHoverProvider("*", {
provideHover(document, position) {
const word = document.getText(document.getWordRangeAtPosition(position));
if (word.split("_").length > 3) {
const i18nPath = "/xxxx/xxxxx/langs";
const jsonUrlCN = i18nPath + "/zh-CN.json";
const jsonUrlEN = i18nPath + "/en.json";
let jsonCN = JSON.parse(fs.readFileSync(jsonUrlCN));
let jsonEN = JSON.parse(fs.readFileSync(jsonUrlEN));
return new vscode. Hover (` I18N plug-in comes to help you through the robbery:
-Chinese: ${jsoncn [word. Tolocalelovercase()]}
-English: ${jsonen [word. Tolocalelovercase()]}
`);
}
},
});
therei18nPath
Of course, it can be configured by users. Next, we’ll study it.
6: Setting configuration
The location of our translation dictionary file must not beWrite dead
In plug-ins, users often need to set their own settings. At this time, we need the concept of vscode setting, as shown in the following figure:
Step 1: initialize configuration items
We comepackage.json
File addsetting
Configuration item:
{
"contributes": {
"configuration": {
"type": "object",
"Title": "I18N translation configuration",
"properties": {
"vscodePluginI18n.i18nPath": {
"type": "string",
"default": "",
"Description": "location of translation file"
},
"vscodePluginI18n.open": {
"type": "boolean",
"default": true,
"Description": "turning on 18N translation"
}
}
}
},
}
type
Set toBoolean
Automatically generatedCheckBox
It’s quite convenient.
Step 2: initial plug-in reading configuration
extension.js
File:
const vscode = require("vscode");
function activate(context) {
const i18nPath = vscode.workspace
.getConfiguration()
.get("vscodePluginI18n.i18nPath");
const open = vscode.workspace.getConfiguration().get("vscodePluginI18n.open");
if (open && i18nPath) {
vscode. window. Showinformationmessage ("I18N translation plug-in in place");
const hover = require("./src/hover");
context.subscriptions.push(hover);
}
}
module.exports = {
activate,
};
Note here that ifconst hover = require("./src/hover");
If it is written at the top, the hovering translation effect may not be closed. There is a pit in this. We will talk about it in detail later.
Step 3: read the path when hovering
hover.js
File:
const vscode = require("vscode");
const fs = require("fs");
module.exports = vscode.languages.registerHoverProvider("*", {
provideHover(document, position) {
const i18nPath = vscode.workspace
.getConfiguration()
.get("vscodePluginI18n.i18nPath");
const open = vscode.workspace
.getConfiguration()
.get("vscodePluginI18n.open");
if (i18nPath && open) {
const word = document.getText(document.getWordRangeAtPosition(position));
if (word.split("_").length > 3) {
const i18nPath = "/xxxxx/xxxx/langs";
const jsonUrlCN = i18nPath + "/zh-CN.json";
const jsonUrlEN = i18nPath + "/en.json";
let jsonCN = JSON.parse(fs.readFileSync(jsonUrlCN));
let jsonEN = JSON.parse(fs.readFileSync(jsonUrlEN));
return new vscode. Hover (` I18N plug-in comes to help you through the robbery:
-Chinese: ${jsoncn [word. Tolocalelovercase()]}
-English: ${jsonen [word. Tolocalelovercase()]}
`);
}
}
},
});
7: When to determine whether to open the plug-in
If inextension.js
The document introduceshover
Module, even if we judge that the user is not enabledI18N translation
The process will also go to the hover module, but if we are judging whether the user is enabled or notI18N translation
Import afterhover
The module will cause that if the user changes the configuration and starts to translate, he can’t respond in time. The user needs to restart, so we need to decide how to design here.
8: Prompt pop-up
If the user turns onI18N translation
However, if the path is not configured, we can actually display a pop-up box to prompt the user whether to fill in the path of the translation dictionary, similar to the effect shown in the following figure:
extension.js
Used in the fileshowInformationMessage
This method, but add two parameters:
const vscode = require("vscode");
function activate(context) {
const i18nPath = vscode.workspace
.getConfiguration()
.get("vscodePluginI18n.i18nPath");
const open = vscode.workspace.getConfiguration().get("vscodePluginI18n.open");
if (open && i18nPath) {
vscode. window. Showinformationmessage ("I18N translation plug-in in place");
const hover = require("./src/hover");
context.subscriptions.push(hover);
} else if (open && !i18nPath) {
vscode.window
"Yes", "message show", "translate file"
.then((result) => {
If (result = = = "yes"){
}
});
}
}
module.exports = {
activate,
};
9: Select file
When the user clicks “yes”, we need to use the API provided by vscode to select the file, and get the return value of the file for active setting:
vscode.window.showOpenDialog
Method, it has four main parameters:
canSelectFiles
Optional filecanSelectFolders
Optional foldercanSelectMany
Can I select more than oneopenLabel
Prompt copy- The return value is the array. The path attribute of the first element is the global path of the file
Finally reuseupdate
Method to actively update the global configuration.
vscode.window
"Yes", "message show", "translate file"
.then((result) => {
If (result = = = "yes"){
vscode.window
.showOpenDialog({
Canselectfiles: false, // optional files
Canselectfolders: true, // is a folder optional
Canselectmany: false, // can multiple be selected
Openlabel: "please select a translation folder",
})
.then(function (res) {
vscode.workspace
.getConfiguration()
.update("vscodePluginI18n.i18nPath", res[0].path, true);
});
}
});
}
end
This is it. I hope to make progress with you.