我尝试将 nanoid 导入 NestJS 并出现此错误:
Error [ERR_REQUIRE_ESM]: require() of ES Module ....
... Instead change the require of index.js in ... to a dynamic import() which is available in all CommonJS modules.
导入代码是:
import { Injectable } from '@nestjs/common';
import { nanoid } from 'nanoid'; //wont import, gives error
import { User } from './data-objects/user.object';
我还尝试了导入语句的变体:
// I tried this alternative
import * as nanoid from 'nanoid';
// Also tried this
const nanoid = require ( 'nanoid' );
没有任何效果。
为什么会出现这个错误,我应该如何在 NestJS 中安装 nanoid?
最佳答案
只有在对 nanoid github issue #365 进行一些研究后,我才能通过简单的搜索找到我的问题的直接答案。找到了答案。
nanoid Ver.4.0.0 于 2022 年 6 月 8 日发布,其中包含重大更改。
它有一个新功能,它现在只支持 ESM 应用程序
这使得它与使用 CommonJS 的应用程序不兼容。 Link to the change log...
nanoid 支持团队 promise 将根据需要继续支持 Ver.3.x.x,直到在 nodejs 和 nestjs 中支持 EMS。
在 NestJS 支持 ESM 的那一天到来之前,您将不得不继续使用 nanoid 版本 3.x.x
npm uninstall nanoid
npm install nanoid@^3.0.0
我的解决方案的来源来自 github 问题 @ayushsharma82 中的评论.
https://stackoverflow.com/questions/73192655/