On page 7 of the tutorial we see chalk package has been installed to make your CLI texts colorful
This is the code given in tutorial:
#!/usr/bin/env node
const arg = require('arg');
const chalk = require('chalk');
try {
const args = arg({
'--start': Boolean,
'--build': Boolean,
});
if (args['--start']) {
console.log(chalk.bgCyanBright('starting the app'));
}
} catch (e) {
console.log(chalk.yellow(e.message));
console.log();
usage();
}
function usage() {
console.log(`${chalk.whiteBright('tool [CMD]')}
${chalk.greenBright('--start')}\tStarts the app
${chalk.greenBright('--build')}\tBuilds the app`);
}
However The chalk module from version 5.0.0 and onwards is an ECMAScript module (ESM), and it no longer supports CommonJS require(). This is why you're going to see an error when you try to require it.
Solution: To use chalk, you need to use dynamic import() instead of require(). Here's how you can do it:
import('chalk').then((chalk) => {
// You can use chalk here
});
Main programming language
JavaScript Node.js: Create a CLI tool in Javascript
Tutorial URL
Page of the problem
On page 7 of the tutorial we see
chalk
package has been installed to make your CLI texts colorful This is the code given in tutorial:However The chalk module from version 5.0.0 and onwards is an ECMAScript module (ESM), and it no longer supports CommonJS require(). This is why you're going to see an error when you try to require it.
Solution: To use chalk, you need to use dynamic import() instead of require(). Here's how you can do it:
New code for the page 7 of the tutorial:
Similar Problem for The Package-Up Method:
Page 8 : https://citw.dev/tutorial/create-your-own-cli-tool?p=8
It should also be dynamically imported like this:
Category