环境准备
- 安装vscode
- 安装nodejs。因为vscode插件是用nodejs开发的
- Yeoman,这是一个前端脚手架工具,可以方便地构造现代化web项目
- VS Code Extension Generator,这是Yeoman的一个插件,专门用来生成vscode插件项目的
1和2的安装不用多说,3和4的安装是通过npm安装的,一条命令一起安装
npm install -g yo generator-code
#生成项目
yo安装完后,通过yo code
命令生成模板项目
这个命令会询问一系列问题,然后根据用户的选择生成最终的项目。vscode推荐的是用TypeScript作为开发语言,官方的文档和示例也都是TypeScript的,所以我们也选择TypeScript。
所有的问题如下所示
# ? What type of extension do you want to create? New Extension (TypeScript)
# ? What's the name of your extension? hello
### Press <Enter> to choose default for all options below ###
# ? What's the identifier of your extension? hello
# ? What's the description of your extension? LEAVE BLANK
# ? Initialize a git repository? Yes
# ? Bundle the source code with webpack? No
# ? Which package manager to use? npm
# ? Do you want to open the new folder with Visual Studio Code? Open with `code`
最后生成项目:
Writing in C:\Users\kevin\git\hello...
create hello\.vscode\extensions.json
create hello\.vscode\launch.json
create hello\.vscode\settings.json
create hello\.vscode\tasks.json
create hello\package.json
create hello\tsconfig.json
create hello\.vscodeignore
create hello\webpack.config.js
create hello\vsc-extension-quickstart.md
create hello\.gitignore
create hello\README.md
create hello\CHANGELOG.md
create hello\src\extension.ts
create hello\src\test\runTest.ts
create hello\src\test\suite\extension.test.ts
create hello\src\test\suite\index.ts
create hello\.eslintrc.json
从上面可以看到项目的目录结构,是一个我们熟悉的nodejs项目。项目的描述文件是package.json,这也是插件的描述文件和配置文件,我们自己的插件的活动栏、界面、命令等都要在这文件里定义。
项目生成完后会自动安装依赖,根据网络状况,这个过程可能快可能慢,需要耐心等待。
#运行插件
安装完成后,用vscode打开生成的hello项目,按F5运行插件,会弹出一个新的vscode窗口,这个新的vscode就是安装了hello插件的,这个插件默认只实现了一个command,Ctrl+Shift+P调出命令栏,输入hello world可以找到这个command,如图所示:
执行该命令后,在右下角会弹出一个弹窗
第一个插件就完成了!
#插件分析
我们来看下这个简单的command是怎么实现的。
首先,在package.json里定义一个command
"contributes": {
"commands": [
{
"command": "hello.helloWorld",
"title": "Hello World"
}
]
},
所有的命令、界面等都是定义在contributes结点下。
"command": "hello.helloWorld", 这是定义命令的id
"title": "Hello World"是定义命令的显示名称。
然后在插件的入口文件extension.ts里,注删这个命令
这个命令的内容很简单,就是显示一个提示框
vscode.window.showInformationMessage('Hello World from hello!');
当然我们也可以在这里实现更复杂的逻辑。
关于package.json的contributes里具体可配置什么东西以及格式是什么,可以参考官方的文档
https://code.visualstudio.com/api/references/contribution-points