Today, I needed to reference the MDN docs for JavaScript modules. As I skimmed through the page, something caught my eye: a file name with the .mjs
extension.
My first reaction was confusion. This was my first time seeing a file with that extension. Upon further reading, I learned .mjs
is a special JavaScript file extension to indicate the script uses native JavaScript modules. Hence the “m” prefix to the “js”.
Reasons for using .mjs
as opposed to .js
- For clarity. The
.mjs
file extension is a quick way to indicate the code in the file uses JavaScript modules instead of classic JavaScript. - For parsing. The
.mjs
file extensions lets runtime environments (ie Node.js) and build tools (ie. Babel) know the file should be parsed as a module. - Avoids strict MIME type errors. Files with the
.mjs
extension are imported with thejavascript/esm
MIME-type.
I haven’t written a native JavaScript module (also referred to as ES Module) before, so all this was news to me. It’s nice to see some browser support for JavaScript modules without the need for third party dependencies.