import { Injectable, OnModuleInit } from '@nestjs/common';
@Injectable()
export class PotatoService implements OnModuleInit {
constructor() {}
async onModuleInit(): Promise<void> {
const chalk = (await import('chalk')).default;
console.log(chalk.blue('potato service init'));
}
}
我尝试使用 import(),但出现错误
node:internal/process/promises:289
triggerUncaughtException(err, true /* fromPromise */);
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/potato/Desktop/learn/nest-demo/node_modules/.pnpm/[email protected]/node_modules/chalk/source/index.js from /Users/potato/Desktop/learn/nest-demo/dist/bootstrap.js not supported.
Instead change the require of index.js in /Users/potato/Desktop/learn/nest-demo/dist/bootstrap.js to a dynamic import() which is available in all CommonJS modules.
at /Users/potato/Desktop/learn/nest-demo/dist/bootstrap.js:64:93
at async bootstrap (/Users/potato/Desktop/learn/nest-demo/dist/bootstrap.js:64:20) {
code: 'ERR_REQUIRE_ESM'
}
Node.js v20.10.0
那么如何在nest中导入仅esmodule的包?
使用 import() 不是从 xxx 导入 xxx,但是不起作用
Chalk 版本 5 是一个 pure 'ESM' 包,不能直接在您当前的 CommonJS 项目中使用。以下是您的选择:
--experimental-require-module
标志才能在 CommonJS 中导入 ESM,这并不理想。建议:迁移到 ESM 是实现更有组织、更现代的项目结构的最佳长期方法。”