vs code webview扩展开发中如何导入npm包?

How to import npm packages in vs code webview extension development?

我想使用 npm packages(latextoMathML),但是当我在我的 webview 上使用它时,它在 运行 扩展名上给我错误:未定义的引用被捕获:包名称 (latextoXML) 未定义。 我已经尝试通过 let / var / const 和 require 方法。 我想在我的 js 代码中使用 webview 函数。

不能用通常的方式将npm包导入到​​webview中,例如这样:

var somelibrary = require('somelibrary')

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

查看 Webview API documentation and example code 了解详细说明

为此,请遵循以下最少步骤:

  • 创建新面板时,启用脚本
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>
...
';