如何在vs代码webview扩展开发中导入npm包



我想使用npm包(latextoMathML(,但当我在网络视图中使用它时,它会在运行扩展时出错,即:捕获了未定义的引用:未定义包名(latextoCML(。我已经尝试过使用require方法的let/var/const。我想在我的js代码中使用webview函数。

您不能以通常的方式将npm包导入到webview中,例如:

var somelibrary = require('somelibrary')

相反,您可以将包作为本地资源加载。

有关的详细说明,请参阅Webview API文档和示例代码

要做到这一点,请遵循以下最低步骤:

  • 创建新面板时,启用脚本
const panel = vscode.window.createWebviewPanel(
'viewType',
'view name',
vscode.ViewColumn.One,
{
// Enable javascript in the webview
enableScripts: true
}
);
  • 将npm包路径封装在一个特殊的vscode uri中。这个uri实际上将包含以下字符串:"vscode-resource://file///path-to-extension/node_modules/somelibrary/somelibrary.js">
const libraryPath = vscode.Uri.file(
path.join(extensionPath, 'node_modules', 'somelibrary', 'somelibrary.js')
);
const scriptUri = webview.asWebviewUri(libraryPath);
  • 创建html面板结构时传递路径
return '
...
<script src='$(scriptUri)'></script>
...
';

最新更新