I am trying to use the chalk npm. My code is:
const chalk = require('chalk');
console.log(
chalk.green('All sytems go') +
chalk.orange('until').underline +
chalk.black(chalk.bgRed('an error occurred'))
);
And I receive this error in my terminal when I type node main.js
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/ezell/Documents/CodeX/NPM/node_modules/chalk/source/index.js from /Users/ezell/Documents/CodeX/NPM/main.js not supported.
Instead change the require of index.js in /Users/ezell/Documents/CodeX/NPM/main.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (/Users/ezell/Documents/CodeX/NPM/main.js:1:15) {
code: 'ERR_REQUIRE_ESM'
}
You need to switch to using the
import
keyword, as Chalk 5 only supports ESM modules.So, to fix your code to adapt these changes, you need to...
Edit your
package.json
file to allow ESM imports. Add the following in yourpackage.json
file:Load Chalk with the
import
keyword, as so:If you, however, want to use
require()
, you need to downgrade to Chalk 4. Follow these steps to downgrade.Replace your existing
chalk
key with the following in yourpackage.json
file:Then, run the following command to install Chalk from your
package.json
file. Make sure to run this in the directory in which yourpackage.json
file is in!Use the
require()
statement like normal.In summary, these are the two things you can do.
import
statements.require()
statements.