如何编写 VS Code 扩展

通过为流行的代码编辑器编写自己的扩展来添加缺失的功能。
109 位读者喜欢这篇文章。
woman on laptop sitting at the window

CC BY 3.0 US Mapbox Uncharted ERG

Visual Studio Code (VS Code) 是 Microsoft 为 Linux、Windows 和 macOS 创建的跨平台代码编辑器。 遗憾的是,Microsoft 版本的 VS Code 是在 Microsoft 软件许可下发布的,该许可不是开源许可。 但是,源代码是开源的,以 MIT 许可证发布,并由 VSCodium 项目分发。

与 VS Code 一样,VSCodium 支持扩展、嵌入式 Git 控制、GitHub 集成、语法突出显示、调试、智能代码完成、代码片段等。 换句话说,对于大多数用户来说,使用 VS Code 和 VSCodium 之间没有区别,后者是完全开源的!

什么是 VS Code 扩展?

扩展允许您向 VS Code 或 VSCodium 添加功能。 您可以在 GUI 中或从终端安装扩展。

您还可以构建自己的扩展。 您可能希望学习构建扩展的原因有以下几个:

  1. 添加内容: 如果缺少您想要的功能,您可以创建一个扩展来添加它。
  2. 为了乐趣和学习: 扩展 API 允许您探索 VSCodium 的工作原理,这是一件有趣的事情。
  3. 提升您的技能: 创建扩展可以增强您的编程技能。
  4. 为了名声: 创建对他人有用的扩展可以提高您的公众形象。

安装工具

在开始之前,您必须已经安装了 Node.jsnpm 以及 VS Code 或 VSCodium

要生成扩展,您还需要以下工具:Yeoman,这是一个开源的客户端脚手架工具,可帮助您启动新项目,以及 vscode-generator-code,这是 VS Code 团队创建的 Yeoman 生成器构建。

构建扩展

在本教程中,您将构建一个为应用程序初始化 Docker 镜像的扩展。

生成扩展骨架

要全局安装和运行 Yeoman 生成器,请在命令提示符或终端中输入以下内容:

npm install -g yo generator-code

导航到要生成扩展的文件夹,键入以下命令,然后按 Enter 键:

yo code

在提示符下,您必须回答有关扩展的一些问题:

  • 您要创建哪种类型的扩展? 使用向上和向下箭头选择一个选项。 在本文中,我将仅解释第一个选项,New Extension (TypeScript)(新扩展(TypeScript))
  • 您的扩展名称是什么? 输入您的扩展名称。 我的扩展名为 initdockerapp。(我相信您会有一个更好的名字。)
  • 您的扩展标识符是什么? 保留原样。
  • 您的扩展描述是什么? 写一些关于您的扩展的信息(您也可以稍后填写或编辑)。
  • 初始化 Git 仓库吗? 这将初始化一个 Git 仓库,您可以稍后添加 set-remote
  • 使用哪个包管理器? 您可以选择 yarn 或 npm;我将使用 npm。

Enter 键,它将开始安装所需的依赖项。 最后:

“您的扩展 initdockerapp 已创建!”

太棒了!

检查项目结构

检查您生成的内容和项目结构。 导航到新文件夹并在终端中键入 cd initdockerapp

进入后,键入 .code。它将在您的编辑器中打开,看起来像这样:

需要注意的两个最重要的文件是 package.jsonsrc 文件夹中的 extension.ts

package.json

首先,查看 package.json,它应该看起来像这样:

{
	"name": "initdockerapp",
	"displayName": "initdockerapp",
	"description": "",
	"version": "0.0.1",
	"engines": {
		"vscode": "^1.44.0"
	},
	"categories": [
		"Other"
	],
	"activationEvents": [
		"onCommand:initdockerapp.initialize"
	],
	"main": "./out/extension.js",
	"contributes": {
		"commands": [
			{
				"command": "initdockerapp.initialize",
				"title": "Initialize A Docker Application"
			}
		]
	},
	"scripts": {
		"vscode:prepublish": "npm run compile",
		"compile": "tsc -p ./",
		"lint": "eslint src --ext ts",
		"watch": "tsc -watch -p ./",
		"pretest": "npm run compile && npm run lint",
		"test": "node ./out/test/runTest.js"
	},
	"devDependencies": {
		"@types/vscode": "^1.44.0",
		"@types/glob": "^7.1.1",
		"@types/mocha": "^7.0.2",
		"@types/node": "^13.11.0",
		"eslint": "^6.8.0",
		"@typescript-eslint/parser": "^2.26.0",
		"@typescript-eslint/eslint-plugin": "^2.26.0",
		"glob": "^7.1.6",
		"mocha": "^7.1.1",
		"typescript": "^3.8.3",
		"vscode-test": "^1.3.0"
	}
}
{
	"name": "initdockerapp",
	"displayName": "initdockerapp",
	"description": "",
	"version": "0.0.1",
	"engines": {
		"vscode": "^1.44.0"
	},
	"categories": [
		"Other"
	],
	"activationEvents": [
		"onCommand:initdockerapp.initialize"
	],
	"main": "./out/extension.js",
	"contributes": {
		"commands": [
			{
				"command": "initdockerapp.initialize",
				"title": "Initialize A Docker Application"
			}
		]
	},
	"scripts": {
		"vscode:prepublish": "npm run compile",
		"compile": "tsc -p ./",
		"lint": "eslint src --ext ts",
		"watch": "tsc -watch -p ./",
		"pretest": "npm run compile && npm run lint",
		"test": "node ./out/test/runTest.js"
	},
	"devDependencies": {
		"@types/vscode": "^1.44.0",
		"@types/glob": "^7.1.1",
		"@types/mocha": "^7.0.2",
		"@types/node": "^13.11.0",
		"eslint": "^6.8.0",
		"@typescript-eslint/parser": "^2.26.0",
		"@typescript-eslint/eslint-plugin": "^2.26.0",
		"glob": "^7.1.6",
		"mocha": "^7.1.1",
		"typescript": "^3.8.3",
		"vscode-test": "^1.3.0"
	}
}

如果您是 Node.js 开发人员,那么其中一些内容可能看起来很熟悉,因为 namedescriptionversionscripts 是 Node.js 项目的常见部分。

有一些部分非常重要。

  • engines:声明扩展将支持的 VSCodium 版本
  • categories:设置扩展类型;您可以从 Languages、Snippets、Linters、Themes、Debuggers、Formatters、Keymaps 和 Other 中进行选择
  • contributes:可以用来运行扩展的命令列表
  • main:您的扩展的入口点
  • activationEvents:指定激活事件何时发生。 具体来说,它决定了何时将扩展加载到您的编辑器中。 扩展是延迟加载的,因此在发生激活事件之前不会激活它们

src/extension.ts

接下来,查看 src/extension.ts,它应该看起来像这样:

// The module 'vscode' contains the VSCodium extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from "vscode";
const fs = require("fs");
const path = require("path");

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {

	// 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 "initdockerapp" is now active!');
	
	// The command has been defined in the package.json file
	// Now provide the implementation of the command with registerCommand
	// The commandId parameter must match the command field in package.json
	let disposable = vscode.commands.registerCommand('initdockerapp.initialize', () => {
		// The code you place here will be executed every time your command is executed

		let fileContent =`
		FROM node:alpine
		WORKDIR /usr/src/app

		COPY package.json .
		RUN npm install
		
		COPY . .
		
		EXPOSE 3000
		CMD ["npm", "start"]
		`;
		
		fs.writeFile(path.join(vscode.workspace.rootPath, "Dockerfile"), fileContent, (err:any) => {
			if (err) {
				return vscode.window.showErrorMessage("Failed to initialize docker file!");
			}
			vscode.window.showInformationMessage("Dockerfile has been created!");
		});
	});

	context.subscriptions.push(disposable);
}

// this method is called when your extension is deactivated
export function deactivate() {}

这是您编写扩展代码的地方。 已经有一些自动生成的代码,我将对其进行分解。

请注意,vscode.command.registerCommand 中的名称 initdockerapp.initializepackage.json 中的命令相同。 它有两个参数:

  1. 要注册的命令的名称
  2. 执行命令的函数

需要注意的另一个函数是 fs.writeFile,您将其写入 vscode.command.registerCommand 函数中。 这将在您的项目根目录中创建一个 dockerfile,并附加代码以创建 Docker 镜像。

调试扩展

既然您已经编写了扩展,现在是调试它的时候了。 单击 Run(运行) 菜单,然后选择 Start Debugging(开始调试)(或者直接按 F5)以打开调试窗口。

通过单击 Add Folder(添加文件夹)Clone Repository(克隆仓库) 按钮,在调试窗口中打开项目。

接下来,使用 Ctrl+Shift+P 打开一个命令面板(在 macOS 上,用 Command 键代替 Ctrl),然后运行 Initialize A Docker Application(初始化 Docker 应用程序)

  • 第一次运行此命令时,由于 VSCodium 已启动,因此 activate 函数尚未执行。 因此,调用 activate,并且 activate 函数注册该命令。
  • 如果该命令已被注册,则执行它。

您会在右下角看到一条消息,提示:“Dockerfile has been created!(Dockerfile 已创建!)” 这创建了一个具有一些预定义代码的 Dockerfile,它看起来像这样:

总结

有许多有用的 API 可以帮助您创建要构建的扩展。 VS Code 扩展 API 还有许多其他强大的方法可以使用。

您可以在 VS Code 扩展 API 文档中了解有关 VS Code API 的更多信息。

接下来阅读什么
标签
User profile image.
Ashique Ansari 是一名软件工程师,在印度班加罗尔的 Red Hat 中间件团队工作。 他热爱网络并为开源项目做出贡献,这是一个不断改进和令人兴奋的新技术的空间。 他认为自己是一名黑客,因为他总是使用技术来解决他生活中的问题和雄心壮志。

评论已关闭。

Creative Commons License本作品根据 Creative Commons Attribution-Share Alike 4.0 International License 许可。
© 2025 open-source.net.cn. All rights reserved.