Home >Development Tools >VSCode >Teach you step by step how to develop a translation plug-in in VSCode

Teach you step by step how to develop a translation plug-in in VSCode

青灯夜游
青灯夜游forward
2021-11-19 19:12:278651browse

This article will take you to write a vscode translation plug-in. By implementing a translation plug-in instance, you can become familiar with the common functions and methods of VS Code plug-in development. I hope it will be helpful to friends in need. !

Teach you step by step how to develop a translation plug-in in VSCode

#This article will familiarize you with the common functions and methods of VS Code plug-in development by implementing a translation plug-in instance. Of course, you can go to VS Code Official API and Official GitHub Examples to view and learn. [Recommended study: "vscode introductory tutorial"]

Requirements

For programmers, translation is a very common need, especially for someone like me who is not good at English. programmer.

  • can directly replace the Chinese translation with the variable name

  • delimited word translation, used for comment translation in the source code

Development

Initialize the project

Execute the scaffolding and initialize the project

yo code

Teach you step by step how to develop a translation plug-in in VSCode

hello world

After creating the directory, we can go to the entry file to find the entry file ./src/extension.ts. There is an activemethod## The #

export function activate(context: vscode.ExtensionContext) {
  console.log('Congratulations, your extension "vscode-fanyi" is now active!');
  let disposable = vscode.commands.registerCommand(
    "vscode-fanyi.helloWorld",
    () => {
      vscode.window.showInformationMessage("Hello World from vscode-fanyi!");
    }
  );
  context.subscriptions.push(disposable);
}

active method is the entry method of the plug-in. A

vscode-fanyi.helloWorld method is registered and the activation is configured in package.json

The event, and the title of the execution event is

Hello World Press F5

to debug, a new vscode extended debugging window will automatically open, and you can see it by executing the command The following effect is shown below.

Teach you step by step how to develop a translation plug-in in VSCodeTranslation API

Translation API I choose to use Youdao Intelligent Cloud

, of course everyone can Choose other translation APIs. The reason for choosing it is because: you get 100 yuan of free trial money when you register, which is enough for personal use.

First create an application, select the service as natural language translation service, and the access method is APITeach you step by step how to develop a translation plug-in in VSCode

Creation completed Then you can get the application ID and secret key. Teach you step by step how to develop a translation plug-in in VSCode

Changed to the Nodejs version based on the official JS demo

"activationEvents": [
    "onCommand:vscode-fanyi.helloWorld"
],
"contributes": {
    "commands": [
        {
            "command": "vscode-fanyi.helloWorld",
            "title": "Hello World"
        }
    ]
}

First, install these 3 packages, among which

crypto-js

generates signatures,

axios Nodejs Request library. Installation

import CryptoJS from "crypto-js";
import axios from "axios";
import querystring from "querystring";

function truncate(q: string): string {
  var len = q.length;
  if (len <= 20) {
    return q;
  }
  return q.substring(0, 10) + len + q.substring(len - 10, len);
}

async function youdao(query: string) {
  var appKey = "3dde97353116e9bf";
  var key = "xxxxxxxxxx"; //注意:暴露appSecret,有被盗用造成损失的风险
  var salt = new Date().getTime();
  var curtime = Math.round(new Date().getTime() / 1000);
  // 多个query可以用\n连接  如 query=&#39;apple\norange\nbanana\npear&#39;
  var from = "AUTO";
  var to = "AUTO";
  var str1 = appKey + truncate(query) + salt + curtime + key;

  var sign = CryptoJS.SHA256(str1).toString(CryptoJS.enc.Hex);

  const res = await axios.post(
    "http://openapi.youdao.com/api",
    querystring.stringify({
      q: query,
      appKey,
      salt,
      from,
      to,
      sign,
      signType: "v3",
      curtime,
    })
  );
  return res.data;
}
Query results

If correct, it must exist in translation

yarn add crypto-js axios querystring

Then change the registration The event is returned asynchronously

{
  "errorCode":"0",
  "query":"good", //查询正确时,一定存在
  "translation": [ //查询正确时一定存在
      "好"
  ],
  "basic":{ // 有道词典-基本词典,查词时才有
      "phonetic":"gʊd",
      "uk-phonetic":"gʊd", //英式音标
      "us-phonetic":"ɡʊd", //美式音标
      "uk-speech": "XXXX",//英式发音
      "us-speech": "XXXX",//美式发音
      "explains":[
          "好处",
          "好的",
          "好",
      ]
  },
}

Let’s take a look at the debugging results

Teach you step by step how to develop a translation plug-in in VSCodeWord replacement

Get the selected text first , then translate, and finally replace the original text after the translation is completed.
let disposable = vscode.commands.registerCommand(
    "vscode-fanyi.helloWorld",
    async () => {
      const res = await youdao(
        &#39;Congratulations, your extension "vscode-fanyi" is now active!&#39;
      );
      vscode.window.showInformationMessage(res.translation[0]);
    }
  );
  context.subscriptions.push(disposable);

Follow the configuration in package.json

export function activate(context: vscode.ExtensionContext) {
  context.subscriptions.push(
    vscode.commands.registerCommand("vscode-fanyi.replace", async () => {
      let editor = vscode.window.activeTextEditor;
      if (!editor) {
        return; // No open text editor
      }
      let selection = editor.selection;
      let text = editor.document.getText(selection);//选择文本

      //有选中翻译选中的词
      if (text.length) {
        const res = await youdao(text);
        //vscode.window.showInformationMessage(res.translation[0]);
        editor.edit((builder) => {
          builder.replace(selection, res.translation[0]);//替换选中文本
        });
      }
    })
  );
}

Add a right-click menu and bind keyboard shortcuts.

The picture below is the vscode official menu grouping. Group them in the modified code section

Let’s take a look at the effectTeach you step by step how to develop a translation plug-in in VSCode

Teach you step by step how to develop a translation plug-in in VSCodeCode word translation

VS code provides a provideHover. When the mouse moves on it, you can perform some specific operations based on the current word. However, in this translation scenario, a single word is not enough, so it must be translated based on the selected word. Let’s take a look at the code.
"activationEvents": [
    "onCommand:vscode-fanyi.replace"
 ],
 "contributes": {
    "commands": [
      {
        "command": "vscode-fanyi.replace",
        "title": "翻译"
      }
    ],
    "keybindings": [
      {
        "command": "vscode-fanyi.replace",
        "key": "ctrl+t",
        "mac": "cmd+t",
        "when": "editorTextFocus"
      }
    ],
    "menus": {
      "editor/context": [
        {
          "when": "editorTextFocus",
          "command": "vscode-fanyi.replace",
          "group": "vscode-fanyi"
        }
      ]
    }
  },

I originally thought that if MarkdownString supports html, the audio of the translation result can also be put into it, but it does not support it. I wonder if any friends have done similar functions. You can communicate in the comment area.

The most critical step is to change

activationEvents

in

package.json to "=onStartupFinished. This can be found in the document Found in .

此激活事件将被发出,并且相关扩展将在VS代码启动后的某个时间被激活。这类似于激活事件,但不会降低VS代码启动的速度。当前,此事件在所有激活的扩展完成激活后发出。

"activationEvents": [
    "onStartupFinished"
  ],

效果

Teach you step by step how to develop a translation plug-in in VSCode

驼峰转换

如果是变量是驼峰命名,可能无法翻译,需要转换下成空格

function changeWord(text: string): string {
  if (!text.includes(" ") && text.match(/[A-Z]/)) {
      const str = text.replace(/([A-Z])/g, " $1");
      let value = str.substr(0, 1).toUpperCase() + str.substr(1);
      return value;
  }
  return text;
}

自定义配置

将有道 appKey 和 appSecret 改成用户扩展配置, 在下 package.json 中的配置 contributes 添加 configuration配置

"configuration": {
  	"title": "Vscode  fanyi",
  	"type": "object",
  	"properties": {
  	  "vscodeFanyi.youdaoApiname": {
  		"type": "string",
  		"description": "youdao appKey"
  	  },
  	  "vscodeFanyi.youdaoApikey": {
  		"type": "string",
  		"description": "youdao appSecret"
  	  },
  	}
  }

就可以在扩展下方填入配置了

Teach you step by step how to develop a translation plug-in in VSCode

然后在代码中 获得配置,并传入到原先的翻译函数中就可以了

const config = vscode.workspace.getConfiguration("vscodeFanyi");
const appKey = config.get("youdaoAppkey") as string;
const appSecret = config.get("youdaoAppSecret") as string;

小结

本插件与 comment-translate 对比

1、API 不同

  • 本插件目前只支持有道,用完免费相当于是付费

  • comment-translate 支持百度谷歌和必应,是免费API

2、实现方式不同

  • 本插件是利用 provideHover 划词翻译,实现起来比较简单

  • comment-translate 是hover 翻译,使用 Language Server Extension Guide 实现起来比较复杂

最后附上链接github

vscode 使用范围在扩大,从extensions market 市场上也可以发现,各种功能的插件基本都很齐全。本篇只介绍了其功能的冰山一角,同时 vscode extensions 开发门槛不高,欢迎大家尝试,或者将有意思的 extensions 推荐在评论区。

希望这篇文章对大家有所帮助,也可以参考我往期的文章或者在评论区交流你的想法和心得,欢迎一起探索前端。

更多关于VSCode的相关知识,请访问:vscode教程!!

The above is the detailed content of Teach you step by step how to develop a translation plug-in in VSCode. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete