Table of Contents
Requirements
Development
Initialize the project
hello world
Translation API I choose to use Youdao Intelligent Cloud
驼峰转换
自定义配置
小结
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

Nov 19, 2021 pm 07:12 PM
vscode

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
Copy after login

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);
}
Copy after login

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"
        }
    ]
}
Copy after login

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;
}
Copy after login
Query results

If correct, it must exist in translation

yarn add crypto-js axios querystring
Copy after login

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":[
          "好处",
          "好的",
          "好",
      ]
  },
}
Copy after login

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);
Copy after login

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]);//替换选中文本
        });
      }
    })
  );
}
Copy after login

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"
        }
      ]
    }
  },
Copy after login

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"
  ],
Copy after login

效果

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;
}
Copy after login

自定义配置

将有道 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"
  	  },
  	}
  }
Copy after login

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

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;
Copy after login

小结

本插件与 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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to define header files for vscode How to define header files for vscode Apr 15, 2025 pm 09:09 PM

How to define header files using Visual Studio Code? Create a header file and declare symbols in the header file using the .h or .hpp suffix name (such as classes, functions, variables) Compile the program using the #include directive to include the header file in the source file. The header file will be included and the declared symbols are available.

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

vscode terminal usage tutorial vscode terminal usage tutorial Apr 15, 2025 pm 10:09 PM

vscode built-in terminal is a development tool that allows running commands and scripts within the editor to simplify the development process. How to use vscode terminal: Open the terminal with the shortcut key (Ctrl/Cmd). Enter a command or run the script. Use hotkeys (such as Ctrl L to clear the terminal). Change the working directory (such as the cd command). Advanced features include debug mode, automatic code snippet completion, and interactive command history.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to solve the problem of vscode Chinese annotations becoming question marks How to solve the problem of vscode Chinese annotations becoming question marks Apr 15, 2025 pm 11:36 PM

How to solve the problem that Chinese comments in Visual Studio Code become question marks: Check the file encoding and make sure it is "UTF-8 without BOM". Change the font to a font that supports Chinese characters, such as "Song Style" or "Microsoft Yahei". Reinstall the font. Enable Unicode support. Upgrade VSCode, restart the computer, and recreate the source file.

Common commands for vscode terminal Common commands for vscode terminal Apr 15, 2025 pm 10:06 PM

Common commands for VS Code terminals include: Clear the terminal screen (clear), list the current directory file (ls), change the current working directory (cd), print the current working directory path (pwd), create a new directory (mkdir), delete empty directory (rmdir), create a new file (touch) delete a file or directory (rm), copy a file or directory (cp), move or rename a file or directory (mv) display file content (cat) view file content and scroll (less) view file content only scroll down (more) display the first few lines of the file (head)

vscode terminal command cannot be used vscode terminal command cannot be used Apr 15, 2025 pm 10:03 PM

Causes and solutions for the VS Code terminal commands not available: The necessary tools are not installed (Windows: WSL; macOS: Xcode command line tools) Path configuration is wrong (add executable files to PATH environment variables) Permission issues (run VS Code as administrator) Firewall or proxy restrictions (check settings, unrestrictions) Terminal settings are incorrect (enable use of external terminals) VS Code installation is corrupt (reinstall or update) Terminal configuration is incompatible (try different terminal types or commands) Specific environment variables are missing (set necessary environment variables)

vscode Previous Next Shortcut Key vscode Previous Next Shortcut Key Apr 15, 2025 pm 10:51 PM

VS Code One-step/Next step shortcut key usage: One-step (backward): Windows/Linux: Ctrl ←; macOS: Cmd ←Next step (forward): Windows/Linux: Ctrl →; macOS: Cmd →

See all articles