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.
The esm module is the format that becomes universal.
When you see that a package is esm only Esm only reference, it means that it can't be imported with require.
If you want to follow this direction, you can modify your CommonJs project to be Esm only.
Once:
the contents of the module script will be evaluated.
The following sample shows how a script element that declare a module script
<script type="module" src="module.mjs"></script>
<script type="module">
// or an inline script
import {foo} from './bar.js';
foo();
</script>
All dependencies (expressed through JavaScript import statements) will be fetched.
// 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";
See https://html.spec.whatwg.org/#integration-with-the-javascript-module-system
import-maps permits to map a name to an URI.
Example:
<script type="importmap">
{
"imports": {
"moment": "https://cdn.jsdelivr.net/npm/[email protected]/dist/moment.js"
}
}
</script>
<script type="module">
import moment from 'moment';
let now = moment().format()
console.log(`The actual date is ${now}`);
</script>
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)
https://github.com/standard-things/esm
require = require("esm")(module/*, options*/)
module.exports = require("./server.js");
with Babel register
require("regenerator-runtime/runtime");
require("@babel/register")({
presets: [
'@babel/preset-env'
]
});
require("./server");
Json Module 1) permits to import data
Example: 2)
<script type="module">
import peopleInSpace from "http://api.open-notify.org/astros.json" assert { type: "json" };
const list = document.querySelector("#people-in-space");
for (const { craft, name } of peopleInSpace.people) {
const li = document.createElement("li");
li.textContent = `${name} / ${craft}`;
list.append(li);
}
</script>