解决 chalk@^5.2.0 的导出问题:require not supported

61 阅读1分钟

Solve - chalk Error [ERR_REQUIRE_ESM]: require not supported

The chalk error "[ERR_REQUIRE_ESM]: require not supported" occurs when you have installed version 5.x of chalk and used the require() method to import it.

chalk Error [ERR_REQUIRE_ESM]: require not supported

Actually, chalk version 5.x is converted to ECMAScript Module (ESM) which means you can import the chalk module using the import statement and not with the require() method.

When you install the chalk package without specifying the version number, then the latest version of it is installed.

$npm install chalk

You can verify which version of chalk is installed by running the following code:

$npm list --depth=0
notes-app@1.0.0 /Users/mohitnatani/Desktop/nodejs-projects/notes-app
|-- chalk@5.0.1
|-- express@4.18.1
|-- lodash@4.17.21
|-- validator@13.7.0

As you can see, chalk version 5.x is installed.

To solve the chalk error "[ERR_REQUIRE_ESM]: require not supported", install the version 4.1.2 by running the following command:

$npm install chalk@4.1.2

The @ symbol is used to specific the exact version of a package.

After installing version 4.1.2, you can use the require() to import the chalk package.

const chalk = require('chalk');

console.log(chalk.green("Chalk package is working"));

Note:  According to the release notes, if you are planning to use chalk with Typescript or any build tool, then it is recommended that you install version 4.x so that you can use require() to import the chalk package.

In case you want to use ES6 import keyword to import the chalk package then write "type":"module" in the package.json file.

package.json

{
  "name": "node-starter",
  "version": "0.0.0",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "type":"module",
  "dependencies": {
    "chalk": "^5.0.1"
  }
}

After adding this line, you can use ES6 import keyword in your code to import the chalk package.

import chalk from 'chalk';

console.log(chalk.green("Chalk package is working"));

To learn more about the chalk npm package, visit this link.

Recommended Posts