插件开发小记

1,193 阅读4分钟

引言

我们经常使用的vscode-plugin-sftp插件,是我们自己开发的插件,常用于调试、发布项目的代码。很好奇,这个东西是怎么做的,翻了翻vscode的文档code.visualstudio.com/api,上手尝试了一下。

vscode插件能做什么?

  1. 通用功能 可以在任何扩展中使用的核心功能,主要包括以下几点:
    • 能够添加命令、配置项、快捷键、菜单项、右键菜单;
    • 存储工作区或全局数据;
    • 展示通知信息;
    • 使用快速选择收集用户的输入;
    • 打开文件选择器让用户去选择文件或文件夹
    • 使用Progress API去阐述长时间运行的操作;
  2. 主题化 控制vscode的外观,包括编辑器中源代码的颜色和vscode ui的颜色,其主要包含三种类型的主题
    • 颜色主题
    • 文件图标主题
    • 产品图标主题
  3. 声明性语言特性 例如括号匹配、自动缩进和语法突出显示;
  4. 程序语言特性 例如悬停、转到定义、诊断错误;
  5. 扩展工作台 工作台是指包含标题栏、活动栏、侧边栏、控制板、编辑组、状态栏等UI组件的整体Visual Studio Code UI。
  6. 调试 可以通过编写将 VS Code 的调试 UI 连接到特定调试器或运行时的调试器扩展来利用 VS Code 的调试功能

环境准备

  • node 最低版本v8.11.3
  • npm 最低版本v6.1.0
  • yeoman
  • generator-code

项目初始化

npm install -g yo

yo模块全局安装后就安装了Yeoman,Yeoman是通用型项目脚手架工具,可以根据一套模板,生成一个对应的项目结构

npm install -g generator-code

generator-code模块是VS Code扩展生成器,与yo配合使用才能构建项目

// 运行
yo code

"图片自定义高度" height="250" width="" "图片自定义高度" height="250" width=""

重要文件

在项目生成之后,目录结构如下所示,其中最重要的文件是package.jsonextension.js

"图片自定义高度" height="" width=""

package.json


{
  "name": "test-extension",// 插件名
  "displayName": "test-extension",// 显示在应用市场的名字
  "description": "我的第一个插件",// 具体描述
  "version": "0.0.1",// 插件的版本号
  "engines": {
    "vscode": "^1.70.0" // 最低支持的vscode版本
  },
  "categories": [
    "Other"// 扩展类别
  ],
  // 激活事件组,在哪些事件情况下被激活
  "activationEvents": [
    "onCommand:test-extension.helloWorld"
  ],
  // 插件的主入口文件
  "main": "./extension.js",
  // 贡献点
  "contributes": {
    // 命令
    "commands": [{
      "command": "test-extension.helloWorld",
      "title": "Hello World"
    }]
  },
  "scripts": {
    "lint": "eslint .",
    "pretest": "yarn run lint",
    "test": "node ./test/runTest.js"
  },
   // 开发依赖项
  "devDependencies": {
    "@types/vscode": "^1.70.0",
    "@types/glob": "^7.2.0",
    "@types/mocha": "^9.1.1",
    "@types/node": "16.x",
    "eslint": "^8.20.0",
    "glob": "^8.0.3",
    "mocha": "^10.0.0",
    "typescript": "^4.7.4",
    "@vscode/test-electron": "^2.1.5"
  }
}


重点关注的主要有三部分内容:activationEventsmain以及contributes,其是整个文件中的重中之重。

main

指明了该插件的主入口在哪,只有找到主入口整个项目才能正常的运转、

activationEvents

指明该插件在何种情况下才会被激活,因为只有激活后插件才能被正常使用,官网已经指明了激活的时机,这样我们就可以按需设置对应时机。(具体每个时机用的时候详细查看即可)code.visualstudio.com/api/referen…

  • onLanguage 打开解析为特定语言文件时被激活,例如"onLanguage:python"
  • onCommand 在调用命令时被激活
  • onDebug 在启动调试话之前被激活
    • onDebugInitialConfigurations
    • onDebugResolve
  • workspaceContains 每当打开文件夹并且该文件夹包含至少一个与 glob 模式匹配的文件时
  • onFileSystem 每当读取来自特定方案的文件或文件夹时
  • onView 每当在 VS Code 侧栏中展开指定 id 的视图
  • onUri 每当打开该扩展的系统范围的 Uri 时
  • onWebviewPanel
  • onCustomEditor
  • onAuthenticationRequest
  • *只要一启动vscode,插件就会被激活
  • onStartupFinished
contributes

通过扩展注册contributes用来扩展Visual Studio Code中的各项技能,其有多个配置。code.visualstudio.com/api/referen…

  • breakpoints 断点
  • colors 主题颜色
  • commands 命令
  • configuration 配置
  • configurationDefaults 默认的特定于语言的编辑器配置
  • customEditors 自定义编辑器
  • ........

extension.json


  • activate 这是插件被激活时执行的函数
  • deactivate 这是插件被销毁时调用的方法

实战

通过在文件编辑区域或文件名上右击弹出按钮,点击按钮获取文件的大小、创建时间和修改时间;

如果获取的是文件夹,则指明该文件是文件夹,不是文件,给予提示。

function activate(context) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "test-extension" is now active!');
// 注册命令
let commandOfGetFileState = vscode.commands.registerCommand('getFileState', uri => {
    // 文件路径
    const filePath = uri.path.substring(1);
    fs.stat(filePath, (err, stats) => {
        if (err) {
            vscode.window.showErrorMessage(`获取文件时遇到错误了${err}!!!`)
        }

        if (stats.isDirectory()) {
            vscode.window.showWarningMessage(`检测的是文件夹,不是文件,请重新选择!!!`);
        }

        if (stats.isFile()) {
            const size = stats.size;
            const createTime = stats.birthtime.toLocaleString();
            const modifyTime = stats.mtime.toLocaleString();

            vscode.window.showInformationMessage(`
                文件大小为:${size}字节;
                文件创建时间为:${createTime};
                文件修改时间为:${modifyTime}
            `, { modal: true });
        }
    });

    const stats = fs.statSync(filePath);
    console.log('stats', stats);
    console.log('isFile', stats.isFile());
});

// 将命令放入其上下文对象中,使其生效
context.subscriptions.push(commandOfGetFileState);
}

发布

安装对应的模块vsce

npm install -g vsce

利用vsce进行打包,生成对应的vsix文件

vsce package

image.png

image.png

image.png

image.png

image.png

问题

问题一: node版本太低,vsce安装不上,最低是14的版本 "图片自定义高度" height="" width=""

解决: 安装nvm版本管理器github.com/coreybutler…

问题二:vsce package没法打包生成对应的vsix文件 解决"图片自定义高度" height="" width="" readme一定要记得修改