如何在用 TypeScript 编写的 VS Code 扩展中导入 ES6 JavaScript 模块?

6 javascript typescript vscode-extensions

我正在使用 TypeScript 开发 VS Code 扩展,并尝试从 npm 导入一个打包"type": "module",在 package.json 中的 JavaScript 库。

如果我简单地这样做,import * as mylib from mylib我会收到此错误消息:

激活扩展“undefined_publisher.curlconverter”失败:必须使用导入来加载 ES 模块:/Users/space/code/curlconverter-extension/curlconverter/node_modules/curlconverter/index.js 不支持 ES 模块的 require()。/Users/space/code/curlconverter-extension/curlconverter/out/extension.js 的 /Users/space/code/curlconverter-extension/curlconverter/node_modules/curlconverter/index.js 的 require() 是一个 ES 模块文件,因为它是一个 .js 文件,其最近的父 package.json 包含 "type": "module" ,它将该包范围内的所有 .js 文件定义为 ES 模块。相反,将 index.js 重命名为以 .cjs 结尾,更改所需代码以使用 import(),或从 /Users/space/code/curlconverter-extension/curlconverter/node_modules/curlconverter/package 中删除 "type": "module"。 json。。

这告诉我,从 TS in 生成的 JSout/extension.js正在使用一个require()语句来尝试加载 ES6 模块,但显然失败了。

我试图让它生成使用的代码,import而不是将这一行添加到我的tsconfig.json

        "module": "ES2020",
Run Code Online (Sandbox Code Playgroud)

但是当我运行扩展的命令时,我收到此错误消息(即使我注释掉该库的导入语句,因此我的扩展只是注册一个不执行任何操作的命令):

激活扩展“undefined_publisher.curlconverter”失败:无法在模块外部使用 import 语句。

Do I need to add a package.json with "type": "module", to out/ or something?

小智 0

如果您的模块必须是 ES6 模块(例如因为它使用 top-level await),那么您不能使用它。VS Code 是一个 Electron 应用程序,Electron 应用程序还不能使用 ES6 模块。

https://github.com/electron/electron/issues/21457