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.
2
Answers
You must notice that the
require()
is a common script directive that it is requesting a module as a common script. I think you can resolve the issue by changing the extension of your module tomjs
.Example:
"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(). 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 disappearThe bigger context here is that Typescript/JavaScript is trying to encourage people to use the new ES6 module system, with
import
andexport
instead of the old CommonJS withrequire()
andexports
.You can use the new ES6 module
import/export
syntax, by marking in thepackage.json
with "type:module" and then instead ofrequire()
you useimport ... from
. But again, you can still userequire()
if you preferSimilar question: Error "File is a commonJS module; it may be converted to an ES6 module. ts(80001)"