Home > Blockchain >  CLI for todo App - help debugging current solution using Commander or change approach to Readline an
CLI for todo App - help debugging current solution using Commander or change approach to Readline an

Time:01-03

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"
  }
}

CodePudding user response:

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

CodePudding user response:

After some more research I found out I was 'muddying the waters' between CJS or ESM modules. CJS modules use require and that is the old way of doing things prior to ES6 modules ESM modules use import

My package.json says type: module telling NodeJS that I am using ESM. But the code is saying CJS.

These are the steps I take to fix this:

  • rename index.js to index.mjs
  • update package.json accordingly
  • replace all require calls with import statements
  • replace module.exports = list with default export = list (or used a named export)
  • Related