@appworks/webview-helper
v0.1.0
Published
封装 VS Code Webview 相关方法和相互通信的 API
Downloads
18
Keywords
Readme
@appworks/webview-helper
封装 VS Code Webview 相关方法和相互通信的 API。
Install
$ npm i @appworks/webview-helper --save
Usage
注册一个 Webview 面板:
// src/extension.ts
import { WebviewPanel } from '@appworks/webview-helper/webview';
export function activate(context) {
const helloWorldPanel = new WebviewPanel(
{
viewType: 'Hello World',
title: 'Hello World',
},
{
scripts: [
vscode.Uri.joinPath(context.extensionUri, 'webview', 'build', 'js', 'main.js'),
],
styles: [
vscode.Uri.joinPath(context.extensionUri, 'webview', 'build', 'css', 'main.css'),
],
},
);
const showHelloWorldCommand = vscode.commands.registerCommand('hello-world.showHelloWorld', () => {
helloWorldPanel.render();
});
}
为 Webview 上下文中传递的消息注册一个消息监听器,并根据在 VS code 上下文中接收到的消息执行代码。
// src/extension.ts
import * as vscode from 'vscode';
import { WebviewPanel } from '@appworks/webview-helper/webview';
export function activate() {
const helloWorldPanel = new WebviewPanel({}, {});
helloWorldPanel.addMessageListener('hello', (text) => vscode.window.showInformationMessage(text));
helloWorldPanel.addMessageListener('getValue', () => {
return 'I am value';
})
}
// webview/pages/index.tsx
import * as React from 'react';
import { vscode } from '@appworks/webview-helper/vscode';
export default function Home() {
React.useEffect(() => {
vscode.executeCommand('getValue').then(value => {
console.log(value);
});
}, []);
return (
<h1
onClick={() => { vscode.postMessage({ command: 'hello', args: ['Hello World'] }); }}
>
Home
</h1>
)
}
在 Webview 注册一个监听器,监听从 VS Code 接受到的信息:
// src/extension.ts
import * as vscode from 'vscode';
import { WebviewPanel } from '@appworks/webview-helper/webview';
export function activate() {
const helloWorldPanel = new WebviewPanel({}, {});
helloWorldPanel.postMessage('hello', ['Hello World'])
}
// webview/pages/index.tsx
import * as React from 'react';
import { vscode } from '@appworks/webview-helper/vscode';
export default function Home() {
vscode.addMessageListener('hello', (text) => {
console.log(text);
});
}