前言
来啦老铁!
这几天琢磨着研究点什么,后来找到一个研究点,那就是:
-
VSCode 插件开发!
玩好 VSCode 插件开发,应该能让自己的工作效率得到提升,可以期待一下~
我们一起来看看怎么开始 VSCode 插件开发的吧~
学习路径
- 安装插件开发脚手架;
- 使用插件开发脚手架创建插件项目;
- 快速试用 Hello World 插件项目;
- 对插件效果稍做解读;
- 对插件做简单改动并验证;
1. 安装插件开发脚手架;
-
首先,我们执行以下命令安装 Yeoman 和 VS Code Extension Generator:
npm install -g yo generator-code

2. 使用插件开发脚手架创建插件项目;
接下来我们利用 yo 和 generator-code 模块配合而成的脚手架,开始创建我们的 VSCode 插件项目。
-
执行命令:
yo code
-
根据脚手架提示选择和填入相关信息:

-
在选项选择完成后,会进行项目依赖的安装:

-
项目依赖安装完成后,可以根据提示打开插件项目:

温馨提示:
想要有这个打开插件项目的提示(Open with 'code'),则需要事先在 VSCode 内 command+shift+p 选择执行:
Shell Command: Install 'code' command in PATH。
这跟很多其他介绍 VSCode 插件开发的文章内,使用 code 命令打开项目的前提一样(如命令:code case2script 可用 VSCode 打开我们的 case2script 项目)。

-
打开项目后,项目结构如:

其实这是个简单的、完整的、可运行的插件项目,接下来我们先来看看这个插件项目工作起来是怎么样子的~
3. 快速试用 Hello World 插件项目;
我们这里先不做任何改动,也不做任何代码介绍,先看看这个最基础的插件运行效果。
-
打开 Extension Developer Host 窗口;
(打开方式有 2 种)
1. 键盘按 F5 打开新窗口(这个麻烦点,不推荐);
众所周知,mac 默认没有 F5 按键(至少我的电脑没有),那按个寂寞?方法是:
a. 点击电脑的系统偏好:System Preferences;

b. 选择 Keyboard;

c. 勾选 Use F1, F2, etc. ... 选项;

d. 按住键盘的 fn 键,在键盘上方的 Touch Bar 上可以看到 F1、F2、、、F12 , 点击 F5 键;

2. 借助 VSCode 工具(简单,推荐);
直接在插件项目内的调试入口内点击调试按钮即可;

两种方式都能打开 Extension Developer Host 窗口,可见,第 2 种方式更简单,用它用它用它!

我们可以在这个窗口任意打开一个项目或文件用于学习演示~
-
运行插件项目;
a. 在Extension Developer Host 窗口内使用键盘组合键:Command+Shift+P (windows 机器是 Ctrl+Shift+P),然后搜索我们的 Hello World 插件:

b. 点击使用我们的 Hello World 插件:

c. 则在 VSCode 右下角则会看到一个提示,这就是我们的插件工作效果:

温馨提示:
这里笔者刚开始遇到一个匪夷所思的问题:死活找不到我们的 Hello World 插件~
网上也没有找到任何有关这方面的介绍,后来怀疑 VSCode 版本问题,于是找到 VSCode 的设置,设置内的版本更新方面的入口,当时刚好有一个更新(未截图),点击后关闭了 VSCode 进行更新(速度很快),更新后自动打开 VSCode,这时候就能找到我们的 Hello World 插件了~

记录一下这个小坑~
4. 对插件效果稍做解读;
-
首先是插件名字何来?
插件名字声明和绑定关系在 package.json 表示,其中:
a. contributes: 是对插件的一些配置,比如图标,菜单、快捷键设置等,例如 title 为我们能在 VSCode 的命令面板中搜索到的插件名字(Command+Shift+P 命令打开的搜索入口);

b. activationEvents: 配置触发 extendion.js 文件中 active 钩子函数的事件,例如:
vscode.commands.registerCommand('case2script.helloWorld'...
c. 其他待详细了解~
-
插件为我们做了什么事情?
extendion.js 中的这行代码为我们注册了一个命令,命令名 case2script.helloWorld 与 package.json 中的 contributes 内的 command 匹配,代表这个插件能够展示一个 information message: Hello World from case2script!

也就是为什么我们在使用了插件之后,在 VSCode 右下角能看到这个提示的原因:

5. 对插件做简单改动并验证;
-
我们可以稍做修改,看下效果,如:

-
点击 reload 即可重新加载插件:

-
点击 reload 即可重新加载插件:

后续,我们可以在这样的基础上进行功能性开发、发布插件到插件市场等,下一篇文章可期~
能力有限,欢迎指正、互相交流,感谢~
如果本文对您有帮助,麻烦点赞、关注!
感谢~
网友评论