【发布时间】:2021-11-20 17:01:38
【问题描述】:
我正在尝试导入其package.json 指定"type": "module" 的包。我看到了Can Typescript import CommonJS Modules?,但它的解决方案 (--allowJs) 对我不起作用。
我尝试在我的tsconfig.json 中为module、moduleResolution、允许allowJs 设置各种值。 esModuleInteropt 和 allowSyntheticDefaultImports 都设置为 true。
我尝试使用import ... from、import(...).then()、import ... = require(...),并将我的index.js 和包的index.js 重命名为index.cjs。当我在节点中运行时,它们都会导致相同的错误:
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" 的其他包。
上次我试图解决这个问题时,我放弃了,选择了一个不同的包。这看起来真的不难做到。
【问题讨论】:
-
“这似乎并不难做到。” 是的,我们现在正处于从旧方式转移到旧方式的不舒服的地方新的方法。最终它会再次变得简单,但是... 新方法必须有所不同是有充分理由的,但它仍然很痛苦。对包作者来说是两倍甚至三倍。
标签: javascript node.js typescript commonjs