nestjs - 如何在 NestJS 中安装 nanoid

我尝试将 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

如何修复

  • 首先卸载 nanoid 4.x.x 版本:npm uninstall nanoid
  • 然后安装 ne 版本和任何其他 future 的 3.x.x:npm install nanoid@^3.0.0

我的解决方案的来源来自 github 问题 @ayushsharma82 中的评论.

https://stackoverflow.com/questions/73192655/

相关文章:

python - 如何处理在 FastAPI 中混淆的路径操作?

r - 计算长数据中行之间的差异

python - 计算 pandas 数据框行中 Python 列表中元素的出现次数

r - 如何在 R 中生成向量的所有可能的连续 n 元组?

javascript - 如何分隔字符串中的标签

rust - 如何在 Rust 中为 Option 实现 From

r - 选择仅连续运行特定值的组

awk - 如何使用 awk 从列表中获取特定列

r - 如何在R中自动使函数的结果成为同一函数的参数

c# - 自定义授权过滤最小 API .Net 6