javascriptnode.jsmjs

What is the difference between .js and .mjs files?


I have started working on an existing project based on Node.js. I was just trying to understand the flow of execution, where I encountered with some *.mjs files. I have searched the web where I found that these are module based JS-files.

I want to know how is it different from *.js files (how does it benefit)?


Solution

  • It indicates an ES6 module file.


    Node.js's original module system is CommonJs (which uses require and module.exports).

    Since Node.js was created, the ECMAScript module system (which uses import and export) has become standard and Node.js has added support for it.

    Node.js will treat .cjs files as CommonJS modules and .mjs files as ECMAScript modules. It will treat .js files as whatever the default module system for the project is (which is CommonJS unless package.json says "type": "module",).

    See also: Differences between ES6 module system and CommonJs