前言
近两日开发了一个在线字典小插件,相比于market中的其他字典插件,我的功能相当简单,但也很轻,算是我开发的第一个完整的 vscode 插件。今后根据需求我还会扩展其功能,或者开发其他的有趣插件。
Installation
首先要确保自己安装了npm。
对于Ubuntu 用户,直接选择
sudo apt-get install nodejs
Visual Studio Code 为开发者提供了一套完整的开发脚手架,可以在npm上进行安装。
npm install -g yo generator-code
通过yo code
来启动一个项目的开发。
yo code
# ? What type of extension do you want to create? New Extension (JavaScript)
# ? What's the name of your extension? online-dictionary
### Press <Enter> to choose default for all options below ###
# ? What's the identifier of your extension? online-dictionary
# ? What's the description of your extension? Self-made online dictionary extension on Visual Studio Code.
# ? Initialize a git repository? Yes
# ? Which package manager to use? npm
code ./online-dictionary
下面打开的 VSCode 目录就是我们的发开项目了。
开发
作为新手,我之前写过一篇VSCode插件开发,其中涉及到很多我之前了解到的VSCode API语法。
我的在线字典主要使用request
包进行数据通信。
Request
通过观察百度翻译的数据传输格式,不难用脚本进行单词通信。
var connect = function (word) {
console.log(`in connect, ${word}`);
var data = {
'kw': word
};
request({
url: 'https://fanyi.baidu.com/sug',
method: 'POST',
headers: {
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
formData: data
}, function (error, response, body) {
if (error) {
console.error(error);
vscode.window.showErrorMessage(error);
}
else {
var result = JSON.parse(body);
console.log(result);
if (result.data.length == 0)
vscode.window.showWarningMessage('not found as a valid english word');
else
vscode.window.showInformationMessage(result.data[0].v)
}
});
};
使用时如下图
打包
vsce是Visual Studio Code Extensions 的缩写,可用于插件的打包、发布、管理等。
安装
npm install -g vsce
Personal Access Token
想要打包或者发布,必须要有一个 publisher,否则会报错“缺少publisher”,还需要对应的 Personal Access Token来进行登陆。
登陆Azure DevOps,若没有组织,新建名为vscode
的organization。
可以在用户设置中找到oken。
选择新建Token,按照下图填写。
在bash中登陆并打包。
vsce create-publisher (publisher name)
vsce login (publisher name)
vsce package
如果需要发布,运行
vsce publish
More to do
-
目前通信有时会不触发
connect
,与网络有关 -
需要增加中译英功能。