【发布时间】:2022-11-23 19:52:07
【问题描述】:
我更新到 nanoid4 并开始收到以下错误:
[ERR_REQUIRE_ESM]: ES模块的require() [...]/node_modules/nanoid/index.js 不受支持。而是改变 需要 [...]/signup_test.ts 中的 index.js 到动态 import() 在所有 CommonJS 模块中都可用
这是它抱怨的导入:
import { customAlphabet } from 'nanoid'这是我正在使用的 tsconfig 文件:
{ "ts-node": { "files": true }, "compilerOptions": { "jsx": "react-jsx", "types": [ "node", "codeceptjs" ], "experimentalDecorators": true, "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "strict": false, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "ES6", "moduleResolution": "node", "resolveJsonModule": true, "incremental": true, "target": "ESNext", }, "include": [ "next-env.d.ts", "**/*.ts", "**/*.tsx" ], "exclude": [ "node_modules" ] }不确定为什么它坏了
【问题讨论】:
-
您是否查看了生成的 Javascript(不是您的 TypeScript 源代码)以查看实际执行的代码。这会更好地告诉我们这里到底发生了什么。我的猜测是您的 TypeScript 设置正在从您的 index.js 生成一个 CommonJS 模块,因此它生成了一个
require('nanoid')这是不合法的,因为nanoid是一个 ESM 模块。所以,也许您的 TypeScript 编译器配置有误。但是,这只是一个猜测。查看生成的 JS 文件会告诉您更多信息。
标签: typescript es6-modules nanoid