โญES module
ES modues are supported by browsers and servers, with a bit of configuration๏ผ
<!-- โญ๏ธ HTML (browser, client-side JS) -->
<!-- โญโโโโ โญ๏ธ โโโโฎ (module mode) -->
<script type="module" src="script.js"></script>// โญ๏ธ (Node.js, server-side JS)
// - add this line to "package.json" file
"type": "module",ES module imports happen before a moduleโs script starts running.
names of dependencies must be quoted strings, not arbitrary expressionsโ
ES module
allows you to have both default export and named exports in one module, unlike CommonJS.
works only via
http(s)://, not locally (file://)โ๏ธalways works in strict modeโ๏ธ
has its own top-level scope, top-level variables and functions from a module are not seen in other scriptsโ๏ธ
should export what they want to be accessible from outside and import what they need.
can make global variables by explicitly assigning them to window, e.g.
window.user = "John"(not recommendedโ๏ธ) (๐๐ป compare with next pointโ๏ธ)If the same module is imported multiple times, its code is executed only once, upon the first importโ๏ธ(โญ๏ธ exports are generated & shared between importers)
bare modules
modules without any path are called โbareโ modules.
such modules are not allowed in import.
references of imported JS files must start with: "
/", "./", or "../"โ๏ธ
๐ก๏ธ ES module always works in strict mode.
// โญ๏ธ import โญโโ โญ๏ธ โโโโฎ
import {sayHi} from './sayHi.js'; // โญ๏ธ must start with: "/", "./", or "../"
// โญ๏ธ import all the exports
import * as moduleObj from './module.js'
// โญ๏ธ export
export { a, b }; // โญ๏ธ export { ... }
export { a as a2, b }; // โญ๏ธ export { A as B, ... }
// โญ๏ธ export default
export default obj;
import obj from "./module.js"; // โญ๏ธ without `{}`, not `{obj}`โ๏ธ
import defaultExport, {otherExport, ...} from "./module.js";replit โฉ
V8.dev โฉ Dynamic import() โญ๏ธโญ๏ธโญ๏ธ
web.dev โฉ Using CSS Module Scripts to import stylesheets โญ๏ธ
Kyle โฉ JS ES6 Modules โญ๏ธ
MakeUseOf โฉ How to Import and Export Functions in JavaScript
async scripts
Cross-Origin Scripts
Scripts fetched from another origin (e.g. another site) require CORS headers, as described in the chapter Fetch: Cross-Origin Requests. ๐ JS.info โฉ External scripts
<!-- another-site.com must supply Access-Control-Allow-Origin -->
<!-- otherwise, the script won't execute -->
<script type="module" src="http://another-site.com/their.js"></script>Last updated
Was this helpful?