The Difference Between MJS, CJS, and JS Files in Node.js
By default, most JavaScript files in Node.js projects have a .js file extension. You might also see JavaScript files with .mjs or .cjs extensions. This page explains the differences, and has suggestions about which one you should use.
Common.js Modules vs ECMAScript Modules
In Node.js, a file is treated as a “module”. JavaScript code in one module (file) can’t be seen from another module (file), unless one module explicitly exports functionality and the other module explicitly imports that functionality.
There are two common systems for imports and exports in Node: Common.js Modules and ES Modules.
Common.js Modules
The older, default module system is called Common.js. If you see imports and exports that look like this, it’s Common.js format:
// `require` for imports
const fs = require("fs");
function loadData(filename) {
const content = fs.readFileSync(filename);
return content.toString();
}
// `module.exports` for exports
module.exports = {
loadData,
};
By default, Node.js will expect Common.js-style modules for files that have a .js or .cjs extension.
ES Modules
The ES module system is the more modern, official option for JavaScript. It uses the import and export keywords like this:
// import with `import`
import fs from "fs";
// export with `export`
export function loadData(filename) {
const content = fs.readFileSync(filename);
return content.toString();
}
To use the ES module system in Node.js, change the file extension to .mjs or add this line to your package.json file if you want to use ES modules with .js file extensions:
"type": "module",
Here’s an example of a minimal package.json file that will work with ES modules:
{
"name": "my-project",
"type": "module"
}
Other JavaScript File Extensions
Here are some other JavaScript file extensions that you might see, though they serve different purposes than the Common.js and ES module systems:
.jsx and .tsx Files
JSX and TSX files are typically used with React, but are increasingly found elsewhere, like with Bun and Hono.
.gjs Files
If you see .gjs files in a project, it’s probably for Glimmer/Ember.js.
Summary
In summary, Node.js uses the Common.js module system by default for files with a .js or .cjs extension. If you want to use ES modules, use a .mjs file extension or set "type" to "module" in the package.json file if you want your files to have .js extensions.
For the full documentation of each system, check out these links: