創建VS Code 擴展插件

VS Code提供了強大的擴展功能,我們可以通過開發插件實現自己的業務模型編輯器。這裡我們快速介紹一下插件的創建、開發和發布過程。

創建插件開發模板

首先需要確認系統中安裝了node.js,並且可以使用npm安裝程式包。然後,安裝插件的開發模板生成器:

npm install -g yo generator-code

安裝完成後,使用模板創建第一個擴展項目,我們為這個項目創建一個子目錄,然後進入命令行,在這個子目錄下執行:

yo code

模板生成程式運行:

生成完成後,在命令行運行:

code .

這個項目在vs code 中打開了:

插件運行和調試

我們打開extension.js文件,可以看到插件啟動的程式碼,我們對程式碼進行一點修改:

將裡面的提示修改為我們需要的資訊。然後按F5運行。這時,一個新的Vs Code介面啟動了,在這個新介面中按Ctrl+Shift+P,打開命令窗口,輸入hello world,在介面下方出現我們編輯的資訊:

說明這個插件已經可以運行了。

插件打包

現在我們看如何將這個插件打包,在其它機器上安裝使用。Vs Code的插件可以同時創建vsix文件發布,也可以發布到應用商店,通過插件管理器進行安裝。我們這裡只介紹第一種方式。

首先需要安裝插件打包工具vsce:

npm i vsce -g

然後,我們還需要在package.json中增加publisher的資訊:

	"publisher": "zhenlei",

如果不增加這個資訊,會出現如下錯誤:

然後還要修改打包工具創建的Readme.md文件,如果不修改,會出現如下錯誤:

現在我們可以打包了,在命令行中,進入項目文件夾,運行:

vsce package

這時會提問,缺少respository,這是一個警告,我們可以忽略,繼續執行,安裝包就創建完成了:

擴展插件的安裝和卸載

可以在vs code的擴展管理器中安裝打包好的擴展插件,選擇從VSIX安裝:

也可以在擴展管理器中禁用或卸載安裝好的插件:

創建第一個實用插件

現在我們創建一個實用的插件,這個插件使用XLST模板將XML文件轉換為另一種格式。轉換功能使用開源的組件xslt-processor完成,插件本身功能很簡單:打開xlst文件,轉換當前的xml,將結果顯示在新的窗口。

首先使用模板創建項目:

yo code

輸入這個項目的名字zlxslt,這個項目我們使用yarn作為包管理器。項目創建完成後,使用

code .

在VS Code中打開項目。
現在需要引入xslt-processor,在終端中輸入:

yarn add xslt-processor

這個命令會在項目中安裝xslt-processor並更新項目中的package.json和yarn.lock。
在src目錄中增加文件schema.d.ts,增加聲明語句:

declare module 'xslt-processor';

修改package.json,去掉預設創建的命令,增加新的命令:

	"activationEvents": [
		"onCommand:zlxslt.runMyXSLT"
	],

修改extension.ts:

// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import * as fs from 'fs';
import { xmlParse, xsltProcess } from 'xslt-processor';
// 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 "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 deactivated
export function deactivate() {}

啟動調試,會打開新的窗口,打開一個xml文件,然後按Ctrl+Shift+p打開命令窗口,選擇「Run My XSLT」,這時會彈出文件選擇窗口,選擇xslt文件,轉換後的xml會顯示在旁邊的窗口。