如何创建VS Code 扩展插件

2022-04-16 15:59:32
目录
创建插件开发模板插件运行和调试插件打包扩展插件的安装和卸载创建第一个实用插件

VS Code提供了强大的扩展功能,我们可以通过开发插件实现自己的业务模型编辑器。这里我们快速介绍一下插件的创建、开发和发布过程。

创建插件开发模板

首先需要确认系统中安装了node.js,并且可以使用npm安装程序包。然后,安装插件的开发模板生成器:

npm install -g yo generator-code

安装完成后,使用模板创建第一个扩展项目,我们为这个项目创建一个子目录,然后进入命令行,在这个子目录下执行:

yo codeur extension is activatedconsole.log('Congratulations, your extension "zlxslt" is now active!');const mydisposable: vscode.Disposable = vscode.commands.registerCommand('zlxslt.runMyXSLT', async (): Promise<any> => {        const xsltFile = await vscode.window.showOpenDialog(            {                canSelectFiles: true,                canSelectFolders: false,                canSelectMany: false,                filters: {                    'XSLT' : ['xsl','xslt']                }            }        );        if(vscode.window.activeTextEditor !== undefined && xsltFile !== undefined) {            const xml: string = vscode.window.activeTextEditor.document.getText();            const xslt: string = fs.readFileSync(xsltFile[0].fsPath).toString();            try {                const rXml = xmlParse(xml);                const rXslt = xmlParse(xslt);                const result = xsltProcess(rXml, rXslt);                const textDoc = await vscode.workspace.openTextDocument(                    {                        content: result,                        language: 'xml'                    }                );                                vscode.window.showTextDocument(textDoc, vscode.ViewColumn.Beside);                                       }            catch(e) {                vscode.window.showErrorMessage(e);            }        }        else {            vscode.window.showErrorMessage('An error occurred while accessing the XML and/or XSLT source files. Please be sure the active window is XML, and you have selected an appropriate XSLT file.');        }    });context.subscriptions.push(mydisposable);}// this method is called when your extension is deactivatedexport function deactivate() {}

启动调试,会打开新的窗口,打开一个xml文件,然后按Ctrl+Shift+p打开命令窗口,选择“Run My XSLT”,这时会弹出文件选择窗口,选择xslt文件,转换后的xml会显示在旁边的窗口。