Search code examples
javascriptnode.jscommand-line-interfacereadlinenode-commander

CLI for todo App - help debugging current solution using Commander or change approach to Readline and Event Emitter?


I am trying to build a CLI for a node js only todo app using commander and conf modules in node js, with chalk to colour the output . I am not sure how to resolve the errors being returned:

ReferenceError: require is not defined in ES module scope, you can use import instead This file is being treated as an ES module because it has a '.js' file extension contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

I'm getting the above error for both conf and commander

Any suggestions on how I could go about debugging this, or changing approach to using readline and events/EventEmitter would be better, will be appreciated, Thanks

Below is a REDACTED version of code:

list.js

const conf = new (require('conf'))();
const chalk = require('chalk');

function list() {
  const todoList = conf.get('todo-list');
  if (todoList && todoList.length) {
    console.log(
      chalk.blue.bold(
        'Tasks in green are done. Tasks in yellow are still not done.'
      )  
     }
    }

module.exports = list;

index.js file

const { program } = require('commander');
const list = require('./list');
program.command('list').description('List all the TODO tasks').action(list);
program.command('add <task>').description('Add a new TODO task').action(add);
program.parse();

package.json file

{
  "main": "index.js",
  "type": "module",
  "keywords": [],
  "dependencies": {
    "chalk": "^5.0.0",
    "chalk-cli": "^5.0.0",
    "commander": "^8.3.0",
    "conf": "^10.1.1"
  },
  "bin": {
    "todos": "index.js"
  }
}

Solution

  • In your package.json you have:

    "type": "module",
    

    This means files with the .js suffix are assumed to be ECMAScript rather than CommonJS. If you want to use CommonJS you can change the file suffix or change the "type" property.

    Or you can use the new syntax. In ECMAScript you use import, in CommonJS you use require.

    To read more about "type" see: https://nodejs.org/dist/latest-v16.x/docs/api/packages.html#determining-module-system