VSCodeで下のバーに時間を表示させるExtensionを書いてみた

皆さんVSCode使ってますか...

・Language Serverがすごい

拡張機能たくさん

・書きやすい!

なので使いましょう()

拡張機能書きやすいっていうのもひとつの魅力

自分で改造できるのはひとつのお楽しみですよね

「これ自分で作ったんやで(ドヤ顔)」

かっこいいですよね

やってみた手順

1.yo code でテンプレート作成

yoとgenerator-codeを入れて

yo code

を実行(Qiitaにいっぱいあると思います)

extension.jsにこんなものが

import { StatusBarAlignment } from 'vscode';

// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');

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

    // 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 "helloworld" 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('extension.sayHello', function () {
        // 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!');
       
    });

    context.subscriptions.push(disposable);
}
exports.activate = activate;

// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;

僕は一行目コメントアウトしました(なんかエラーでたため)

2.下のバーへのアクセス

今回やりたいのは下のバー(StatusBar)に時間を表示させるというものです

補完を頼って探すと

vscode.window.createStatusBarItemというものが見つかります

function createStatusBarItem(alignment?: StatusBarAlignment, priority?: number): StatusBarItem;

第一引数...右よりか左よりか

第二引数...優先順位

戻りを受け取って,itemなどとすると

item.text = "...";

で設定でき

item.show();

で表示できました、簡単!

3.動作のタイミング設定

https://vscode-doc-jp.github.io/docs/extensionapi/activation-events.html

これの通りですね 今回は拡張機能を読み込んだ際にactivateします

4.時間の表示

setInterval使いました

var item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 10);

    let printDate = function () {
        var date = new Date();
        item.text = date.getHours().toString() + ":" + date.getMinutes().toString() + ":" + date.getSeconds().toString();
        item.show();
    };

    setInterval(printDate,100);

これで一秒ごとに更新してくれます

こんな感じ

f:id:Kutimoti:20180102002823p:plain

しっかり出てます

感想

APIがとってもしっかりしているので書きやすい印象が強かったです

まだまだ書けそう!