Henry
Henry

Reputation: 21

how to import a esModule in nest?

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'));
  }

}

i try to use import(), but get a error

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

so how to import a esmodule only package in nest ?

use import() not import xxx from xxx, but not work

Upvotes: 2

Views: 35

Answers (1)

Giancarlo Sotelo
Giancarlo Sotelo

Reputation: 246

Chalk version 5, being a pure 'ESM' package, can't be directly used in your current CommonJS project. Here are your options:

  1. Migrate your project to ESM (Best): This is the cleanest solution. Your project can then use both ESM and CommonJS modules seamlessly.
  2. Install Chalk version 4 (Easy): A quick fix, but you might miss out on the latest Chalk features. See a demo here.
  3. Use Node.js 22 (Not Recommended): Requires --experimental-require-module flag to import ESM in CommonJS, which is not ideal.
  4. Install Chalk 5 with 'dynamic import': You're missing some necessary configurations. For instance, regardless of using dynamic imports, you'll need TypeScript version 4.7 or higher. For more information on the required configurations, please check this link.

Recommendation: Migrating to ESM is the best long-term approach for a more organized and modern project structure."

Upvotes: 0

Related Questions