0

I'm working on a CLI tool. I used "commander", which is a CommonJS module, to parse command-line arguments. I also want to use "p-map" to manage concurrency. However, "p-map" is a ES6 module.

Also I'm using Typescript.

Now both code editor and Typescript compiler won't complain. However I cannot execute my CLI tool. If I compile with "module":"commonjs", node would not load p-map and complains "Must use import to load ES Module... node_modules/p-map/index.js...require() of ES modules is not supported.". If I compile with "module":"es2015", use "require" to import the CommonJS modules, and add "type":"module" in my package.json, node would complain "ReferenceError: require is not defined".

I love the flexibility of Typescript/Javascript, however, it's time like this makes me miss Java. Java might be too prissy, but I don't spend hours trying to figure out import / export......

So, is it possible to use both CommonJS and ES6 module in a Node.JS command-line program?

3
  • Use ESM and import the cjs module. That should work. Alternatively, as the linked page states, you can use dynamic import for the other way, if really needed. Commented Jun 5, 2021 at 10:20
  • Thanks for responding! I tried ECM import the cjs module, yes it works. I didn't know that I could import cjs module, not just using "require()". I also tried dynamic import. It SHOULD work. However the problem is Typescript always compiles my dynamic import() into require(). Commented Jun 5, 2021 at 11:34
  • Will you please put your response as an answer so I can accept it as the correct answer? Thanks again! Commented Jun 5, 2021 at 11:34

1 Answer 1

2

To enhance compatibility, the (moderately new) node esm loader can import cjs-modules (e.g. import identifier from 'cjs-module-name';).

The other way around doesn't work, you can't require an esm-module, but dynamic import should work, if really necessary.

A related read may be the statement from p-map's owner regarding the topic.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.