Fix - chalk Error [ERR_REQUIRE_ESM]: require not supported

avatar

Borislav Hadzhiev

Fri Feb 18 20222 min read

banner

Photo by Blake Moulton

Fix - chalk Error [ERR_REQUIRE_ESM]: require not supported #

The chalk error "[ERR_REQUIRE_ESM]: require() not supported" occurs because the chalk package has been converted to be an ESM only package in version 5, which means that the package cannot be imported with require() anymore.

chalk err require esm

To solve the chalk error "[ERR_REQUIRE_ESM]: require() not supported", downgrade the version of the package to 4.1.2 by running the following command: npm install chalk@4.1.2 . This is the last version of chalk that is built with CommonJS.

The recommendation in the release notes of the chalk package is that if you're using chalk with TypeScript or a build tool you should downgrade to version 4.1.2.

To install version 4 of chalk, open your terminal in the root directory of your project and run the following command.

shell
npm install chalk@4.1.2

Now you are able to use the chalk package with the require() syntax.

index.js
const chalk = require('chalk'); console.log(chalk.red('Hello world!!! 🎉🎉🎉'));

And here is the output I get in my terminal when I run the code from the snippet.

chalk import success

If your environment supports ES Modules, you should try to convert the require() import to ESM.

index.js
import chalk from 'chalk'; console.log(chalk.red('Hello world!!! 🎉🎉🎉'));

But this might not work, depending on your setup.

The release notes of the chalk package explicitly state that it's fine to stay on v4 for now as it has been stable for years.

Note that if you use TypeScript with version less than 4.6, you should be staying on chalk version 4.x. You can read more about this in this GitHub issue.

Use the search field on my Home Page to filter through my more than 1,000 articles.