Difference Between .js and .mjs Files in JavaScript

Sadat Jubayer

Sadat Jubayer

March 04, 2023

2 min read

JavaScript is a versatile programming language used for both client-side and server-side development. However, you might have come across files with different extensions, such as .js and .mjs, and wondered about their distinctions. In this blog post, we will know the difference between these two file types and explore how they impact our JavaScript projects.

JavaScript (.js) Files

These files are the standard and widely recognized format for JavaScript code. .js files can be executed in any environment that supports JavaScript, such as web browsers, Node.js, and various other JavaScript runtimes. They use the CommonJS module system, where modules are imported using the require keyword and exported using the module.exports syntax. This approach has been the foundation of JavaScript's module ecosystem for a long time.

ES Modules (.mjs) Files

With the advent of ECMAScript 6 (ES6) in 2015, JavaScript introduced a new module system known as ECMAScript Modules, or ES Modules. To differentiate between the traditional CommonJS modules and the new ES Modules, files using the ES module system are given the .mjs extension. ES Modules offer a more standardized, modern, and flexible approach to module management. They are designed to work both in the browser and in Node.js environments, though Node.js requires a specific flag (--experimental-modules) to enable ES Modules support when using .mjs files.

In summary, the difference between .js and .mjs files lies in the module system they utilize. .js files use the traditional CommonJS approach, while .mjs files embrace the modern ECMAScript Modules system. When working on projects that target modern environments or require the benefits of ES Modules, .mjs files offer a more elegant and standardized solution.