.mts
is a cool file extension (TypeScript ES modules)
Published on in JavaScript, Node.js and TypeScript
What's that, a file extension named after me?! Or a file extension for TypeScript files that are always ES modules?
I was reading the
Prettier 2.5 announcement post
the other day
and noticed that
"Prettier will now format files with .mts
and .cts
extensions as TypeScript."
Turns out .mts
is not named after my first name (Matias).
It's for TypeScript files that are always ES modules.
- ES modules (ESM) are JavaScript or TypeScript files
that use the
import
/export
syntax. - CommonJS (CJS) modules are JavaScript or TypeScript files
that use the
require()
/module.exports
syntax.- TypeScript might require special syntax for CommonJS modules (I'm not sure).
Usually JavaScript files use the .js
extension
and TypeScript files use the .ts
extension.
Such files can be either ES modules or CommonJS modules.
The TypeScript 4.5 Beta announcement post explains when the more precise file extensions can be useful (emphasis added):
Node.js supports a new setting in
package.json
calledtype
."type"
can be set to either"module"
or"commonjs"
.This setting controls whether
.js
files are interpreted as ES modules or CommonJS modules, and defaults to CommonJS when not set.[...]
The
type
field inpackage.json
is nice because it allows us to continue using the.ts
and.js
file extensions which can be convenient; however, you will occasionally need to write a file that differs from whattype
specifies. You might also just prefer to always be explicit.Node.js supports two extensions to help with this:
.mjs
and.cjs
..mjs
files are always ES modules, and.cjs
files are always CommonJS modules, and there's no way to override these.In turn, TypeScript supports two new source file extensions:
.mts
and.cts
. When TypeScript emits these to JavaScript files, it will emit them to.mjs
and.cjs
respectively.
There are more details in the first section of the TypeScript 4.5 Beta announcement post.
Some tools may also require or encourage the more precise file extensions.
An analogy:
Vite (a build tool)
supports JSX by default only in .jsx
and .tsx
files
(but not in .js
and .ts
files)
for performance reasons.
Can you think of a file extension that's named after you?