简体   繁体   中英

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

I want to use npm packages(latextoMathML) but when i use it on my webview it gives me error on running the extension that is: undefined refrence caught: package name(latextoXML) not defined. i have tried through let / var / const with require method. i wants to use in my js code under webview function.

You cannot import the npm package into webview in the usual way, for example like this:

var somelibrary = require('somelibrary')

Instead, you can load the package as local resource.

See the Webview API documentation and example code for a detailed explanation

To do this, follow these minimum steps:

  • when creating a new panel, enable scripts
const panel = vscode.window.createWebviewPanel(
            'viewType',
            'view name',
            vscode.ViewColumn.One,
            {
                // Enable javascript in the webview
                enableScripts: true
            }
        );
  • wrap the npm package path in a special vscode uri. This uri will actually contain this string: "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);
  • pass path when creating html panel structure
return '
...
<script src='$(scriptUri)'></script>
...
';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM