Both .js
and .mjs
are file extensions for JavaScript files, but they serve distinct purposes due to how JavaScript handles modules. Here’s a detailed comparison:
1. .js
File Extension
- Default Module Type: Historically,
.js
files were used for non-modular scripts or CommonJS modules in environments like Node.js. - Behavior:
- By default,
.js
files are treated as CommonJS modules in Node.js. - In a browser environment,
.js
files are interpreted as classic scripts unless explicitly treated as ES modules.
- By default,
- Flexibility:
- You can configure
.js
files to behave as ES modules by specifying"type": "module"
in yourpackage.json
file in Node.js.
- You can configure
2. .mjs
File Extension
- Explicit Module Type: The
.mjs
extension explicitly signals that the file is an ECMAScript (ES) module. - Behavior:
- In Node.js, files with the
.mjs
extension are always treated as ES modules, regardless of thepackage.json
configuration. - ES modules use the modern import/export syntax, enabling better tree-shaking and module management.
- In Node.js, files with the
- Use Case:
.mjs
is particularly useful for projects that need a clear distinction between CommonJS and ES module systems.
Key Differences
Feature | .js Files |
.mjs Files |
---|---|---|
Default Module Type | CommonJS (in Node.js, unless configured) | ES Module |
Explicit Declaration | Requires type: "module" in package.json to be ES modules. |
Always treated as ES modules. |
Import/Export Syntax | Uses require() for imports (CommonJS). |
Uses import/export (ES module syntax). |
Compatibility | Backward compatible with older Node.js and browsers. | Designed for modern JavaScript environments. |
Use Case | General JavaScript files; CommonJS modules. | Explicitly ES modules; modern JavaScript. |
When to Use .mjs
vs. .js
- Use
.mjs
when you are working exclusively with ES modules and want to enforce modern module syntax. - Use
.js
when:- You are using CommonJS modules.
- You want flexibility to toggle between CommonJS and ES modules using
package.json
.
Example
.js
File (CommonJS):
// CommonJS syntax
const fs = require('fs');
module.exports = function sayHello() {
console.log('Hello, world!');
};
.mjs
File (ES Module):
// ES Module syntax
import fs from 'fs';
export function sayHello() {
console.log('Hello, world!');
}
Conclusion
.js
files are versatile and compatible with both CommonJS and ES modules depending on your configuration..mjs
files provide a clear signal that the file is an ES module, making them ideal for modern JavaScript applications.