Using modules on the web

Modern browsers have very recently started to implement module loaders natively. To natively use a script that imports modules, you'll have to make its type="module".

Here's a very basic working example in Chrome 63:

// index.html<!doctype HTML><html>    <head>        <script src="index.js" type="module"></script>    </head>    <body>        <div id="text"></div>    </body></html>

This is how index.js (the main script file) will look:

// index.jsimport { writeText2Div as write2Div } from './module.js';write2Div('Hello world!')

This is the module that index.js imports (in the same directory):

// module.jsconst writeText2Div = text => document.getElementByID('text').innerText = text;export { writeText2Div };

This, when tested, should show

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.