Javascript ES - Module Script (esm / .mjs)

About

The module implementation in Ecma Script (ES2015).

An ES6 module is a Javascript file:

Everything inside a module is local to the module. To make it public, you need to export it

This feature is not implemented in any browsers natively at this time. It is implemented in many transpilers.

Modules are deferred, and only run after a document is loaded.

As a browser parses your ES6 module code, it will discover a tree of dependencies that it needs to fetch in order to execute your code. The solution is to bundle them through a builder.

Management

Processing

Once:

the contents of the module script will be evaluated.

Declaration

The following sample shows how a script element that declare a module script

  • an external module script.
<script type="module" src="module.mjs"></script>
<script type="module">
  // or an inline script
  import {foo} from './bar.js';
  foo();
</script>

Dependency

All dependencies (expressed through JavaScript import statements) will be fetched.

Aggregating modules

// import "foo" and re-export some of its exports
export {bar, bar1} from "foo";

// import "bar" and export ALL of its exports
export * from "bar";

Integration with HTML

Node loader

Node does not support natively the ESM module but with the help of a loader monitor, the loaded code can be compiled to the commonjs format (node format)

Esm

https://github.com/standard-things/esm

require = require("esm")(module/*, options*/)
module.exports = require("./server.js");

Babel

with Babel register

require("regenerator-runtime/runtime");
require("@babel/register")({
    presets: [
        '@babel/preset-env'
    ]
});
require("./server");

Documentation / Reference


Powered by ComboStrap