ECMAScript Modules (ESM) is aspecification 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.
Theexport keyword allows to expose things from an ESM to other modules:
exportconstCONSTANT=42;exportlet variable=42;// only reading is exposed// it's not possible to modify the variable from outsideexportfunctionfun(){ console.log('fun');}exportclassCextendsSuper{method(){ console.log('method');}}let a, b, other;export{ a, b, otheras c};exportdefault1+2+3+more();Theimport keyword allows to get references to things from other modules into an ESM:
import{CONSTANT, variable}from'./module.js';// import "bindings" to exports from another module// these bindings are live. The values are not copied,// instead accessing "variable" will get the current value// in the imported moduleimport*as modulefrom'./module.js';module.fun();// import the "namespace object" which contains all exportsimport theDefaultValuefrom'./module.js';// shortcut to import the "default" exportBy 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 thepackage.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 thetext/javascript orapplication/javascript mime type will also force module type to ESM.
In addition to the module format, flagging modules as ESM also affect the resolving logic, interop logic and the available symbols in modules.
Imports in ESM are resolved more strictly. Relative requests must include a filename and file extension (e.g.*.js or*.mjs) unless you have the behaviour disabled withfullySpecified=false.
Requests to packages e.g.import "lodash" are still supported.
Only the "default" export can be imported from non-ESM. Named exports are not available.
CommonJs Syntax is not available:require,module,exports,__filename,__dirname.
HMR can be used withimport.meta.webpackHot instead ofmodule.hot.