javascript

Trouble using require(); Needing to convert JS file to ES module


When I use require() in my JS file, I get the following error: File is a CommonJS module; it may be converted to an ES module.

Why is it so? And how can I use require, ie, convert my JS file into an ES module?

I have tried to append "type":"module" to my javascript file, and that didn't help solve the problem.

I want to use require(). How can I do that? Also, I am a bit of a newbie to JS so thank you for your patience.


Solution

  • "File is a CommonJS module; it may be converted to an ES module"

    This is not error, just a warning. You can still use commonjs and require() (provided that the package supports CommonJs). It will still work. Preferrably, you can change your extension name to .cjs to mark your file as a commonjs file and the warning should disappear

    The bigger context here is that Typescript/JavaScript is trying to encourage people to use the new ES6 module system, with import and export instead of the old CommonJS with require() and exports.

    You can use the new ES6 module import/export syntax, by adding to the package.json this property: "type": "module" and then instead of require() you use import ... from.

    Many modern packages have changed to support ES6 modules, so it is recommended that you also use ES6 module syntax. But again, you can still use require() if you prefer if the package you import supports commonjs

    Similar question: Error "File is a commonJS module; it may be converted to an ES6 module. ts(80001)"