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. !
#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
hello world
After creating the directory, we can go to the entry file to find the entry file ./src/extension.ts
. There is an active
method## 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
Hello World Press
F5
Translation 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 API
Creation completed Then you can get the application ID and secret key.
"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='apple\norange\nbanana\npear' 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 querystringThen 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
Word 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(
'Congratulations, your extension "vscode-fanyi" is now active!'
);
vscode.window.showInformationMessage(res.translation[0]);
}
);
context.subscriptions.push(disposable);
Follow the configuration in package.jsonexport 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 effect
Code 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
inpackage.json to
"=onStartupFinished. This can be found in the
document Found in .
此激活事件将被发出,并且相关扩展将在VS代码启动后的某个时间被激活。这类似于激活事件,但不会降低VS代码启动的速度。当前,此事件在所有激活的扩展完成激活后发出。
"activationEvents": [ "onStartupFinished" ],
效果
驼峰转换
如果是变量是驼峰命名,可能无法翻译,需要转换下成空格
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" }, } }
就可以在扩展下方填入配置了
然后在代码中 获得配置,并传入到原先的翻译函数中就可以了
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 实现起来比较复杂
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!

The main difference between the free and paid versions of VisualStudio is the richness of features and the service supported. The free version (Community) is suitable for individual developers and small teams, providing basic development tools; the paid version (Professional and Enterprise) provides advanced features such as advanced debugging and team collaboration tools, suitable for large projects and enterprise-level development.

VisualStudioCommunityEdition is a free IDE suitable for individual developers, small teams and educational institutions. 1) It provides functions such as code editing, debugging, testing and version control. 2) Based on the Roslyn compiler platform, it supports multiple programming languages and integrates Git and TFVC. 3) Advanced features include unit testing, optimization suggestions include turning off unnecessary extensions and using a lightweight editor.

VisualStudio is an integrated development environment (IDE) developed by Microsoft, which supports a variety of programming languages, including C#, C, Python, etc. 1. It provides IntelliSense function to help write code quickly. 2. The debugger allows setting breakpoints, step-by-step code execution, and identifying problems. 3. For beginners, creating a simple console application is a great way to get started. 4. Advanced usage includes the application of design patterns such as project management and dependency injection. 5. Common errors can be solved step by step through debugging tools. 6. Performance optimization and best practices include code optimization, version control, code quality inspection and automated testing.

VisualStudio is suitable for large-scale projects and enterprise-level application development, while VSCode is suitable for rapid development and multilingual support. 1. VisualStudio provides a comprehensive IDE environment and supports Microsoft technology stack. 2.VSCode is a lightweight editor that emphasizes flexibility and scalability, and supports cross-platform.

Yes, some versions of VisualStudio are free. Specifically, VisualStudioCommunityEdition is free for individual developers, open source projects, academic research, and small organizations. However, there are also paid versions such as VisualStudioProfessional and Enterprise, suitable for large teams and enterprises, providing additional features.

Cross-platform development with VisualStudio is feasible, and by supporting frameworks like .NETCore and Xamarin, developers can write code at once and run on multiple operating systems. 1) Create .NETCore projects and use their cross-platform capabilities, 2) Use Xamarin for mobile application development, 3) Use asynchronous programming and code reuse to optimize performance to ensure efficient operation and maintainability of applications.

The ways to format JSON in VS Code are: 1. Use shortcut keys (Windows/Linux: Ctrl Shift I; macOS: Cmd Shift I); 2. Go through the menu ("Edit" > "Format Document"); 3. Install JSON formatter extensions (such as Prettier); 4. Format manually (use shortcut keys to indent/extract blocks or add braces and semicolons); 5. Use external tools (such as JSONLint and JSON Formatter).

Compiling code in VSCode is divided into 5 steps: Install the C extension; create the "main.cpp" file in the project folder; configure the compiler (such as MinGW); compile the code with the shortcut key ("Ctrl Shift B") or the "Build" button; run the compiled program with the shortcut key ("F5") or the "Run" button.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools