codecrafters-io / build-your-own-x

Master programming by recreating your favorite technologies from scratch.
https://codecrafters.io
282.04k stars 26.46k forks source link

`Node.js: Create a CLI tool in Javascript` tutorial needs package import method update #976

Open ShatilKhan opened 6 months ago

ShatilKhan commented 6 months ago

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:

#!/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
});

New code for the page 7 of the tutorial:

#!/usr/bin/env node
const arg = require('arg');

try {
    const args = arg({
        '--start': Boolean,
        '--build': Boolean,
    });

    if (args['--start']) {
        import('chalk').then((chalk) => {
            console.log(chalk.default.bgCyanBright('starting the app'));
        });
    }
} catch (e) {
    import('chalk').then((chalk) => {
        console.log(chalk.default.red(e.message));
        console.log();
        usage();
    });
}

function usage() {
    import('chalk').then((chalk) => {
        console.log(`${chalk.default.whiteBright('tool [CMD]')}
        ${chalk.default.greenBright('--start')}\tStarts the app
        ${chalk.default.greenBright('--build')}\tBuilds the app`);
    });
}

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:

import('package-up').then((pkgUp) => {
  const pkgPath = pkgUp.packageUpSync({cwd: process.cwd()});
    const pkg = require(pkgPath);
       if (pkg.tool){
         console.log('Found Config', pkg.tool);
       }else{
          console.log('No config found, using default');
        }
           import('chalk').then((chalk) => {
          console.log(chalk.default.bgCyanBright('starting the app'));
     });
 });

Category