Home > Article > Development Tools > Teach you step by step how to develop a translation plug-in in 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. !
#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"]
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
Execute the scaffolding and initialize the project
yo code
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
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.
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='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
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);
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 effect
Code word translation
"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" } ] } },
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!