如何创建您的第一个Visual Studio代码扩展

news/2024/8/26 17:41:49

介绍 (Introduction)

Visual Studio Code is a code editor from Microsoft available on Windows, Linux, and macOS. It offers extensions that you can install through the Visual Studio Code MarketPlace for additional features in your editor. When you can’t find an extension that does exactly what you need, it is possible to create your own. In this article, you’ll create your first Visual Studio Code extension.

Visual Studio Code是Microsoft提供的代码编辑器,可在Windows,Linux和macOS上使用。 它提供了扩展,您可以通过Visual Studio Code MarketPlace安装这些扩展,以用于编辑器中的其他功能。 如果找不到能完全满足您需求的扩展程序,则可以创建自己的扩展程序。 在本文中,您将创建第一个Visual Studio Code扩展。

先决条件 (Prerequisites)

  • Node.js installed on your machine following How To Install Node.js and Create a Local Development Environment.

    按照如何安装Node.js和创建本地开发环境的要求 ,在计算机上安装了Node.js。

安装工具 (Installing the Tools)

The Visual Studio Code team created a generator for creating extensions, which generates all of the necessary starter files to begin creating your extension.

Visual Studio Code团队创建了一个用于创建扩展程序的生成器,该生成器生成了所有必要的启动程序文件以开始创建扩展程序。

To get started, you’ll need to have Yeoman installed, which is a scaffolding tool. You can install Yeoman by running

首先,您需要安装Yeoman ,这是一种脚手架工具。 您可以通过运行安装Yeoman

  • npm install -g yo

    npm install -g yo

With Yeoman installed, now you need to install the specific generator for Visual Studio Code extensions:

安装Yeoman之后,现在您需要安装Visual Studio Code扩展的特定生成器:

  • npm install -g yo generator-code

    npm install -g yo生成器代码

创建您的第一个扩展 (Creating Your First Extension)

You are now ready to create your first extension. To do so, run the following command.

现在您可以创建您的第一个扩展。 为此,请运行以下命令。

  • yo code

    哟代码

You will then answer several questions about your project. You will need to choose what kind of extension you are creating and between TypeScript and JavaScript. We will be choosing JavaScript in this tutorial.

然后,您将回答有关您的项目的几个问题。 您将需要选择要创建的扩展类型以及TypeScript和JavaScript之间的扩展。 在本教程中,我们将选择JavaScript。

Then you’ve got a few more questions.

然后,您还有其他问题。

  • name

    名称
  • identifier

    识别码
  • description

    描述
  • type checking (yes)

    类型检查(是)
  • do you want to initialize a git repository (yes)

    您是否要初始化git存储库(是)

After this process is complete, you’ve got all of the files you need to get started. Your two most important files are:

完成此过程后,您便拥有了开始所需的所有文件。 您最重要的两个文件是:

  • package.json

    package.json

  • extension.js

    extension.js

Open package.json and let’s take a look. You’ll see the name, description, and so on. There are two more sections that are very important.

打开package.json ,让我们看一下。 您将看到名称,描述等。 还有两个非常重要的部分。

  • activationEvents: this is a list of events that will activate your extension. Extensions are lazy loaded so they aren’t activated until one of these activation events occur.

    activationEvents :这是将激活您的扩展程序的事件列表。 扩展是延迟加载的,因此直到这些激活事件之一发生之前​​,它们不会被激活。

  • commands: list of commands that you provide the user to run via your extension.

    commands :您提供给用户的通过扩展运行的命令列表。

We will come back to these shortly.

我们将很快回到这些。

You can also take a look at the extension.js file. This is where we are going to write the code for our extension. There’s some boilerplate code in here, so let’s break it down.

您也可以查看extension.js文件。 这是我们要为扩展编写代码的地方。 这里有一些样板代码,所以让我们分解一下。

In the highlighted line below is where our command is being registered with VS Code. Notice that this name extension.helloworld is the same as the command in package.json. This is intentional. The package.json defines what commands are available to the user, but the extension.js file registers the code for that command.

在下面突出显示的行中,我们的命令已在VS Code中注册。 请注意,此名称extension.helloworldpackage.json的命令相同。 这是故意的。 package.json定义了用户可以使用的命令,但是extension.js文件注册了该命令的代码。

In this Hello World example, all this command will do is display a Hello World message to the user.

在此Hello World示例中,此命令所要做的只是向用户显示Hello World消息。

调试扩展 (Debugging Your Extension)

Now that we have all of the necessary files installed, we can run our extension.

现在我们已经安装了所有必需的文件,我们可以运行扩展程序。

The .vscode folder is where VS Code stores configuration files of sorts for your project. In this case it includes a launch.json that contains debug configurations.

.vscode文件夹是VS Code在其中存储项目的各种配置文件的位置。 在这种情况下,它包含一个包含调试配置的launch.json

From here, we can debug. Open the debug tab on the left on the left of your screen, and then click play.

从这里,我们可以调试。 打开屏幕左侧的调试标签,然后点击播放

This will open up a new (debug) instance of VS Code.

这将打开一个新的(调试)VS Code实例。

With this debug instance of VS Code open, you can open the command palette with Cmd + SHIFT + P on Mac or CTRL + SHIFT + P on Windows and run "Hello world".

在此VS Code调试实例打开的情况下,您可以在Mac上使用Cmd + SHIFT + P或在Windows上使用CTRL + SHIFT + P打开命令面板,然后运行"Hello world"

You’ll see a hello world message pop up in the lower right hand corner.

您会在右下角看到一个世界问候消息。

编辑扩展 (Editing Your Extension)

Before we work on code, let’s take one more look at the activationEvents section in the package.json file. Again, this section contains a list of events that will activate our extension whenever they occur. By default, it is set to activate when our command is run.

在编写代码之前,让我们再看一下package.json文件中的activationEvents部分。 同样,此部分包含事件列表,这些事件将在发生任何事件时激活我们的扩展程序。 默认情况下,它设置为在运行我们的命令时激活。

In theory, this event could be anything, and more specifically * anything. By setting the activation event to * this means your extension will be loaded when VS Code starts up. This is not required by any means, just a note.

从理论上讲,此事件可能是任何事情,更具体地讲*任何事情。 通过将激活事件设置为*这意味着您的扩展程序将在VS Code启动时加载。 不需要任何方式,仅需注意。

We’ve got the necessary files and we know how to debug. Now let’s start building our extension. Let’s say we want this extension to be able to create an HTML file that already has boilerplate code in it and is added into our project.

我们已经有了必要的文件,并且知道如何调试。 现在开始构建扩展程序。 假设我们希望此扩展名能够创建一个已经包含样板代码并将其添加到我们的项目中HTML文件。

Let’s first update the name of our command. In extension.js, update the name of the command from extension.helloworld to extension.createBoilerplate.

首先让我们更新命令的名称。 在extension.js ,将命令名称从extension.helloworld更新为extension.createBoilerplate

Now, update the package.json file accordingly witht he change in command.

现在,在不更改命令的情况下,相应地更新package.json文件。

Now, let’s write our functionality. The first thing we’ll do is require a couple of packages. We are going to use the fs (file system) and path modules.

现在,让我们编写我们的功能。 我们要做的第一件事是需要几个软件包。 我们将使用fs (文件系统)和path模块。

const fs = require("fs");
const path = require("path");

We also need to get the path to the current folder. Inside of the command, add the following snippet:

我们还需要获取当前文件夹的路径。 在命令内部,添加以下代码段:

const folderPath = vscode.workspace.workspaceFolders[0].uri
        .toString()
        .split(":")[1];

We will also need to store our boilerplate HTML code into a variable so that we can write that to a file. Here’s the boilerplate HTML:

我们还需要将样板HTML代码存储到变量中,以便可以将其写入文件中。 这是样板HTML:

const htmlContent = `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <link rel="stylesheet" href="app.css" />
</head>
<body>
    <script src="app.js"></script>
</body>
</html>`;

Now we need to write to the file. We can call the writeFile function of the file system module and pass in the folder path and HTML content.

现在我们需要写入文件。 我们可以调用文件系统模块的writeFile函数,并传入文件夹路径和HTML内容。

Notice that we use the path module to combine the folder path with the name of the file we want to create. Then inside of callback, if there is an error, we display that to the user. Otherwise, we let the user know that we created the boilerplate file successfully:

请注意,我们使用路径模块将文件夹路径与要创建的文件名结合在一起。 然后在回调内部,如果有错误,我们将其显示给用户。 否则,我们会让用户知道我们成功创建了样板文件:

fs.writeFile(path.join(folderPath, "index.html"), htmlContent, err => {
        if (err) {
          return vscode.window.showErrorMessage(
            "Failed to create boilerplate file!"
          );
        }
        vscode.window.showInformationMessage("Created boilerplate files");
      });

Here’s what the full function looks like:

这是完整功能的样子:

const folderPath = vscode.workspace.workspaceFolders[0].uri
        .toString()
        .split(":")[1];

      const htmlContent = `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <link rel="stylesheet" href="app.css" />
</head>
<body>
    <script src="app.js"></script>
</body>
</html>`;

      fs.writeFile(path.join(folderPath, "index.html"), htmlContent, err => {
        if (err) {
          return vscode.window.showErrorMessage(
            "Failed to create boilerplate file!"
          );
        }
        vscode.window.showInformationMessage("Created boilerplate files");
      });
    }

Go ahead and debug your newly developed extension. Then, open up the command palette and run “Create Boilerplate” (remember we changed the name).

继续并调试您新开发的扩展。 然后,打开命令面板并运行“ Create Boilerplate”(记住我们已更改名称)。

After running the command, you’ll see the newly generated index.html file and a message to let the user know:

运行该命令后,您将看到新生成的index.html文件和一条消息,通知用户:

结论 (Conclusion)

To learn more about what APIs there are to use and how to use them, read through the Visual Studio Code Extension API documentation.

要了解有关使用什么API以及如何使用它们的更多信息,请通读Visual Studio Code Extension API文档 。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-create-your-first-visual-studio-code-extension


http://www.niftyadmin.cn/n/3649409.html

相关文章

网站添加免费SSL证书——HTTPS协议

在添加证书之前首先了解两个概念&#xff1a;SSL和HTTPS。 ▶ SSL(Secure Sockets Layer 安全套接层),及其继任者传输层安全(Transport Layer Security&#xff0c;TLS)是为网络通信提供安全及数据完整性的一种安全协议。TLS与SSL在传输层与应用层之间对网络连接进行加密。 ▶ …

使用React Native Web构建适合移动设备的Web应用

介绍 (Introduction) Over the years, building web applications that are mobile friendly has become easier with the advent of media queries and the introduction of service workers. Using media queries, we could make web applications that different shapes whe…

sql server和Navicat使用遇到错误解决办法

sql server忘记密码和用户名:http://www.cnblogs.com/xushining/p/3752667.html navicat连接失败:http://blog.csdn.net/lsd123/article/details/5548827

afinal框架(FinalAcitivity,FinalBitmap,FinalDb,FinalHttp 四大模块)

github下载地址&#xff1a;https://github.com/yangfuhai/afinal Afinal是一个android的ioc&#xff0c;orm框架&#xff0c;内置了四大模块功能&#xff1a;FinalAcitivity,FinalBitmap,FinalDb,FinalHttp。通过finalActivity&#xff0c;我们可以通过注解的方式进行绑定ui和…

[WiX]我的第一个WiX安装脚本

我的第一个WiX安装脚本 WiX的Wiki&#xff1a;WiX 代表 Windows Installer Xml (WiX) toolset 它是建立Windows Installer的XML toolset (MSI) 包裹从XML 文件。它支持开发商集成他们的发布过程建立MSI 和MSM 设定包裹的命令行环境。内部结构Wix 由四份组成: 蜡烛、光、Lit 和…

WordPress添加侧栏小工具-博客统计(网站统计)

WordPress侧边栏“博客统计”小工具的制作方法。首先要下载cztcms.zip文件&#xff0c;解压得到一个PHP文件。蓝奏云地址&#xff1a;▶ cztcms.zip 1、将这个PHP文件放到主题目录下。打开主题目录下的function.php&#xff0c;在最后一个 ?> 前插入以下代码&#xff1a; i…

every 和some_如何使用.every()和.some()操纵JavaScript数组

every 和some介绍 (Introduction) ES5 and ES6 brought many changes to JavaScript, including better ways of working with a collection of data expressed as arrays. While the language has significantly improved support for declarative data manipulation on array…

PhotoView的使用

1. 功能介绍 特性(Features)&#xff1a; 支持Pinch手势自由缩放。支持双击放大/还原。支持平滑滚动。在滑动父控件下能够运行良好。&#xff08;例如&#xff1a;ViewPager&#xff09;支持基于Matrix变化&#xff08;放大/缩小/移动&#xff09;的事件监听。 优势&#xff1…