Closed13
VS Code エクステンションで Web API にアクセスする

このスクラップについて
このスクラップでは VS Code エクステンション開発で Web API にアクセスする方法を調べる過程を記録する。

前のスクラップ

普通に fetch を使えるようだ
Web の場合は CORS の設定が必要になる。
Cloud Storage などを使ってエンドポイントを用意して CORS を設定しよう。

Cloud Storage 必要ないかも
アクセスできるかどうかを調べるだけならそれこそ serve コマンドで良さそうだ。

プロジェクト作成
コマンド
cd ~/workspace
npx --package yo --package generator-code -- yo code
コンソール出力
? What type of extension do you want to create? New Web Extension (TypeScript)
? What's the name of your extension? hello-fetch
? What's the identifier of your extension? hello-fetch
? What's the description of your extension?
? Initialize a git repository? Yes
? Which bundler to use? webpack
? Which package manager to use? npm

サーバー起動
コマンド
npx serve --cors -l 8000 --ssl-cert $HOME/certs/localhost.pem --ssl-key $HOME/certs/localhost-key.pem
動作確認には curl を使える。
コマンド
curl https://localhost:8000/package.json

OutputChannel
前回のスクラップの復習を兼ねて OutputChannel を使ってみよう。
src/web/extension.ts
import * as vscode from "vscode";
export function activate(context: vscode.ExtensionContext) {
const outputChannel = vscode.window.createOutputChannel("Hello Fetch");
const disposable = vscode.commands.registerCommand(
"hello-fetch.helloWorld",
() => {
outputChannel.append("TEST");
outputChannel.show();
}
);
context.subscriptions.push(disposable);
}
export function deactivate() {}

fetch を使ってみる
src/web/extension.ts
import * as vscode from "vscode";
export function activate(context: vscode.ExtensionContext) {
const outputChannel = vscode.window.createOutputChannel("Hello Fetch");
const disposable = vscode.commands.registerCommand(
"hello-fetch.helloWorld",
async () => {
const response = await fetch("https://localhost:8000/package.json");
const text = await response.text();
outputChannel.append(text);
outputChannel.show();
}
);
context.subscriptions.push(disposable);
}
export function deactivate() {}
無事に package.json の内容が表示された

@vscode/test-web で試してみる
コマンド
npx @vscode/test-web --extensionDevelopmentPath=.
OK

VS Code for the Web で試してみる
VS Code for the Web で Developer: Install Extension From Location...
を実行して Location には https://localhost:8000
を指定する。
こちらも OK

おまけ:OutputChannel に URL が含まれている場合
VS Code では Command + クリックでブラウザを開けるが VS Code for the Web では下記のようになった。
新しいタブを開く方法があれば良いのだがあるのだろうか?

あった
src/web/extension.ts
import * as vscode from "vscode";
export function activate(context: vscode.ExtensionContext) {
const outputChannel = vscode.window.createOutputChannel("Hello Fetch");
const disposable = vscode.commands.registerCommand(
"hello-fetch.helloWorld",
async () => {
vscode.env.openExternal(
vscode.Uri.parse("https://localhost:8000/package.json")
);
}
);
context.subscriptions.push(disposable);
}
export function deactivate() {}
ありがとう Stack Overflow。

おわりに
これで Web API にアクセスして何らかの処理を行って、結果を Web ページで表示するみたいなエクステンションが作れそうだ。
このスクラップは3ヶ月前にクローズされました