0
votes

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?

1
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.ASDFGerte
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().Bing Ren
Will you please put your response as an answer so I can accept it as the correct answer? Thanks again!Bing Ren

1 Answers

1
votes

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.