javascript - 从 CommonJS TypeScript 导入 es 模块文件

标签 javascript node.js typescript commonjs

我正在尝试导入一个包,其中它的 package.json 指定 "type": "module"。我看到了Can Typescript import CommonJS Modules? , 但它的解决方案 (--allowJs) 对我不起作用。

我尝试在我的 tsconfig.json 中为 modulemoduleResolution、allow allowJs 设置各种值. esModuleInteroptallowSyntheticDefaultImports 都设置为 true

我试过使用 import ... fromimport(...).then()import ... = require(. ..),并将我的 index.js 和包的 index.js 重命名为 index.cjs。当我在 Node 中运行时,它们都会导致相同的错误:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: E:\src\...\node_modules\stringify-object\index.js
require() of ES modules is not supported.
require() of E:\src\...\node_modules\stringify-object\index.js from E:\src\...\index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename E:\src\...\node_modules\stringify-object\index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from E:\src\...\node_modules\stringify-object\package.json.

我尝试从包的 package.json 中删除 "type": "module",但它依赖于其他包 "type": "module ".

上次我试图解决这个问题时,我放弃了,选择了另一个包。这看起来真的不应该很难做到。

最佳答案

我找到了我认为的解决方法。如果我在 tsconfig.json 中设置 "module": "ESNext" 并将输出重命名为 index.mjs,它就可以工作。不过,它并不是特别优雅。只是必须有更好的方法。

我很乐意接受一个不同的、更好的答案。


正如评论中指出的那样,在我项目的 package.json 中设置 "type": "module" 就可以了,所以我不需要重命名 index.jsindex.mjs

关于javascript - 从 CommonJS TypeScript 导入 es 模块文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69365351/

相关文章:

javascript - 在 Knockout JS 中处理多维数组的最佳方法是什么?

javascript - 为什么.splice总是删除最后一个元素?

javascript - 摩卡单元测试 : Uncaught TypeError: Cannot read property 'apply' of undefined

node.js - 无法使用 pm2 和 ts-node 运行 typescript node.js 应用程序

Angular:如何在有多个下拉菜单的 ng-bootstrap 下拉菜单中检测切换状态

javascript - 正则表达式匹配字符和字母

php - 通过回显将日期时间/时间戳从 PHP 传递到 Javascript

node.js - JupyterLab plotly 扩展错误 : Cannot find module jupyter\lab\staging\node_modules\ejs\postinstall. js

javascript - 当使用 Promise.reject 生成数组时,我得到了成功响应

node.js - TS2403 : Subsequent variable declarations must have the same type. NPM 安装后