ECMAScript Modules (ESM) is a
specification
for using Modules in the Web.
It's supported by all modern browsers and the recommended way of writing modular code for the Web.
Webpack supports processing ECMAScript Modules to optimize them.
Exporting
The
export
keyword allows to expose things from an ESM to other modules:
export const CONSTANT = 42;
export let variable = 42;
export function fun() {
console.log('fun');
export class C extends Super {
method() {
console.log('method');
let a, b, other;
export { a, b, other as c };
export default 1 + 2 + 3 + more();
Importing
The
import
keyword allows to get references to things from other modules into an ESM:
import { CONSTANT, variable } from './module.js';
import * as module from './module.js';
module.fun();
import theDefaultValue from './module.js';
Flagging modules as ESM
By default webpack will automatically detect whether a file is an ESM or a different module system.
Node.js established a way of explicitly setting the module type of files by using a property in the
package.json
.
Setting
"type": "module"
in a package.json does force all files below this package.json to be ECMAScript Modules.
Setting
"type": "commonjs"
will instead force them to be CommonJS Modules.
"type"
:
"module"
In addition to that, files can set the module type by using
.mjs
or
.cjs
extension.
.mjs
will force them to be ESM,
.cjs
force them to be CommonJs.
In DataURIs using the
text/javascript
or
application/javascript
mime type will also force module type to ESM.