skip to Main Content

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


  1. 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 to mjs.

    Example:

    // some-file.js
    const imported = require('module.mjs');
    
    // module.mjs
    export default { file: import.meta.url };
    
    Login or Signup to reply.
  2. "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 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 marking in the package.json with "type:module" and then instead of require() you use import ... from. But again, you can still use require() if you prefer

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search