Vscode series: make a translation plug-in with all five zang organs


The effect is as follows: it is a translation function~
Vscode series: make a translation plug-in with all five zang organs

It needs to be prepared

  • Baidu translation developer account, get appid and key
  • npm install -g yo generator-code

Key vscodeapi

  • Gets the text selected by the current active editor
vscode.window.activeTextEditor.document.getText(range?: Range)
  • Call quick select panel
vscode.window.showQuickPick(items: string[] | Thenable<string[]>, options?: QuickPickOptions)

Start coding

Scaffold create folder code

yo code

Select JavaScript (extension), and then press enter. The default is OK.

Baidu translation api code


Here you need to know how to get the user configuration. After all, the same appid and key call times are limited. The following steps are required.

In vscode, menus, commands, views and other functions need to be displayed in front of users package.json Registered contribution points
The contribution configuration items are as follows

"contributes": {
    "configuration": [
        "title": "translateNamed",
        "properties": {
          "translate.appid": {
            "type": "string",
            "default": "20200921000570318",
            "Description": "Baidu translation API appid"
          "translate.secret": {
            "type": "string",
            "default": "8iaGzb7v0225xQ8SVxqq",
            "Description": "Baidu translation API key"
  • User configuration found

    OK, after registering the contribution point, you can find the configuration item just registered through the API

vscode.workspace.getConfiguration().get((section: string))
  • Call API

    I’m used to itaxiosthereforeyarn add axios md5I’ve got a lot of themmd5Baidu translation API is required.

OK, here is thetranslate-api.jsThe code for.

const axios = require("axios")
const vscode = require("vscode")
const md5 = require("md5")
const appid = vscode.workspace.getConfiguration().get("translate.appid")
const secret = vscode.workspace.getConfiguration().get("translate.secret")

module.exports = {
   *Translation methods
   *@ param {string} Q query string
   *@ param {string} from source language
   *@ param {string} to target language
   * @returns {{data: {trans_ Result: [{SRC: string, DST: String}]} promise translation result
  translate(q, from, to) {
    var salt = Math.random()
    return axios({
      method: "get",
      url: "https://fanyi-api.baidu.com/api/trans/vip/translate",
      params: {
        sign: md5(appid + q + salt + secret),

If you need to replace it with other translation API, such as Google translation, you only need to change this APItranslate-api.jsJust the code.

Operation vscode

go back toextension.jsIn the middle.

First, we need to find the text selected by the current editor.

const currentEditor = vscode.window.activeTextEditor
const currentSelect = currentEditor.document.getText(currentEditor.selection)

amongcurrentEditor.document.getTextWhat the method needs isRangeBut because ofselectionInherited fromRangeYou can justcurrentEditor.selectionPut it in the parameter.

The second step is to segment the words.

The translated words are generally separated by spaces, so they can be separated by spaces.

const list = result.split(" ")
const arr = []
//- connection
arr.push(list.map((v) => v.toLocaleLowerCase()).join("-"))
//Underline connection
arr.push(list.map((v) => v.toLocaleLowerCase()).join("_"))
//Great hump
arr.push(list.map((v) => v.charAt(0).toLocaleUpperCase() + v.slice(1)).join(""))
//Small hump
    .map((v, i) => {
      if (i !== 0) {
        return v.charAt(0).toLocaleUpperCase() + v.slice(1)
      return v.toLocaleLowerCase()

The third step is to put the results into the quick selection panel.

let selectWord = await vscode.window.showQuickPick(arr, {
  Placeholder: "please select the variable name to be replaced,",

Step 4: replace the selected text with the selected result

if (selectWord) {
  currentEditor.edit((editBuilder) => {
    editBuilder.replace(currentEditor.selection, selectWord)

To view all the code, you can go to GitHub:github

The entry file isextension.js

For more convenience, register the menu

For more convenience, click the registration menu.

  "menus": {
    "editor/context": [
        "when": "editorHasSelection",
        "command": "translate.zntoen",
        "group": "navigation"

Among them,

whenWhen menu options appear,editorHasSelectionWhen the editor has selected text. What are the other options available at when?Vscode when contribution point document

commandIt refers to the command to be executed when clicking the menu

groupIt refers to the place where the menu is placed. What other options are available?Vscode group document

Add Icon

In package.json Medium configuration

"icon": "images/icon.png",

Where images/ icon.png It’s 128 * 128 pixels.

Add git warehouse, modify readme, etc

If you don’t add git repository, there will be a warning when publishing.

If you do not modify the readme, you will not be able to publish!

Create account token

First of all, you must create a Microsoft account, and then open the following link


In the upper right corner, click User Settings > personal access tokens
Vscode series: make a translation plug-in with all five zang organs

Follow the prompts for new token

When choosing a range, choose this way

Vscode series: make a translation plug-in with all five zang organs

Sign in

vsce create-publisher your-publisher-name


vsce publish

Plug in address:https://marketplace.visualstudio.com/items?itemName=chendm.translate&ssr=false#overview

Vscode searchtranslateNamedTo experience.

GitHub View Code:https://github.com/chendonming/translate

Recommended Today

JS function

1. Ordinary function Grammar: Function function name (){ Statement block } 2. Functions with parameters Grammar: Function function name (parameter list){ Statement block } 3. Function with return value Grammar: Function function name (parameter list){ Statement block; Return value; } Allow a variable to accept the return value after calling the function Var variable name […]