Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
1 min readJavaScriptNode

How Node treats .js and .mjs files

Use file extensions and the package type to choose between CommonJS and ES modules in Node.

In Node, .mjs means ES module and .cjs means CommonJS. A .js file can use either system, depending on the nearest parent package.json. Set its type field to make the choice explicit.

Choose the package type

  • "type": "module" makes .js files in the package use ES modules, with import and export.
  • "type": "commonjs" makes them use CommonJS, with require() and module.exports.

If you need one file to use a different system, give it the explicit extension. In a CommonJS package, for example, save an ES module script as tools.mjs and run node tools.mjs.

The .mjs and .cjs extensions decide the format. For .js, start with the type field in the nearest package.json.

Browser modules

For scripts loaded in a browser, <script type="module" src="./app.js"></script> selects module mode. You can use either extension as long as your server sends a JavaScript media type such as text/javascript.

Node supported ES modules without the experimental flag before this post was published. See the Node module history for the release timeline.

diagram

Two module systems, one decade

ES modules joined JavaScript in 2015, reached Node behind a flag in 2017 and became stable in Node 14.

Update, November 2026. Node enabled syntax detection by default in 22.7.0. An ambiguous .js file with ES module syntax can now run as a module even without an explicit type.