VS Code拡張機能のコマンドをコマンドパレットから実行する – 【VS Code】

VS Code拡張機能のコマンドをコマンドパレットから実行する – 【VS Code】

VS Code拡張機能のコマンドを実行してみます。

前提

  • TypeScriptで開発
  • npm,node.js,yo,generator-codeなどインストール済み(npm install -g yo generator-code)
  • yo codeで作成済み

package.json

package.jsonに書かれているコマンドを実行してみます。contributesセクションに1つコマンドが登録されています。

titleでは、コマンドパレットに入力する値を指定します。

commandでは、拡張機能のメインのtsファイル(src/extension.ts)のregisterCommand関数で書かれているコマンドIDを指定します。

package.json

  "contributes": {
    "commands": [
      {
        "command": "sampleext.helloWorld",
        "title": "Hello World"
      }
    ]
  },

拡張機能のアクティベーション時にこのregisterCommandで対応する関数が登録されて初めて動作します。コマンドがコマンドパレットで実行されると、この登録済みの関数が実行されます。

extension.ts

	const disposable = vscode.commands.registerCommand('sampleext.helloWorld', () => {
		// The code you place here will be executed every time your command is executed
		// Display a message box to the user
		vscode.window.showInformationMessage('Hello World from SampleExt!');
	});

テスト

F5を押すと新しいVS Codeが起動するので、ctrl + shift + pで「>hello world」とタイプして実行します。

多言語対応(ローカライズ)

プロジェクト直下にpackage.nls.jsonとpackage.nls.ja.jsonを作成してtitleの多言語対応が出来ます。

package.jsonのtitleを修正します。

%で囲む必要があり、ドットで区切って階層的にキー整理する慣習のようです。ここでは%hello%とします。

package.json

  "contributes": {
    "commands": [
      {
        "command": "sampleext.helloWorld",
        "title": "%hello%" 
      }
    ]
  },

package.nls.jsonを作成します。

package.nls.json

{
  "hello": "Hello World"
}

package.nls.ja.jsonを作成します。

package.nls.ja.json

{
  "hello": "こんにちは世界"
}

多言語対応(ローカライズ)のテスト

テストする前に、ctrl + shift + pで「>configure display language」と入力し、「日本語(ja)」を選択します。VS Codeを再起動します。

F5を押してデバッグし、新たに起動するVS Code上でctrl + shift + pで「>Hello World」と入力すると日本語も表示されることが確認できます。

株式会社CONFRAGE ITソリューション事業部をもっと見る

今すぐ購読し、続きを読んで、すべてのアーカイブにアクセスしましょう。

続きを読む

タイトルとURLをコピーしました