ES Modules — New browsers are starting to support it

Before 2015 there wasn’t a native way to work with modules into JavaScript. Developers started to find different ways to implement it: for example splitting the codebase into separated files and scopes, using AMD with file loaders like RequireJS or just making CommonJS work in the browser through Browserify or other libraries.

In June 2015 the spec for the 6th edition of JavaScript changed things a lot. Finally a native way of working with modules. But it was really hard to implement on the web platform — so module bundlers like Webpack just allowed us to write code and generate a script understandable by the browser.

But finally modules are starting to be supported into the browsers. Safari 10.1 is the first browser that allows us to use native modules. But also into other browsers it’s possible to use it. Actually are supported in:

  • Safari 10.1.
  • Chrome Canary 60 — behind the Experimental Web Platform flag in chrome:flags.
  • Firefox 54 — behind the dom.moduleScripts.enabled setting in about:config.
  • Edge 15 — behind the Experimental JavaScript Features setting in about:flags.

Just try to create a script element with the type=module

<script type="module">   
import {addText} from './test.js';
addText('Lorem Ipsum.');
</script>

And into test.js

export function addText(text) {   
const div = document.createElement('div');
div.textContent = text;
document.body.appendChild(div);
}

Not all module specifiers are supported yet. A valid module specifiers should be one of this:

  • A full non-relative URL. As in, it doesn’t throw an error when put through new URL(moduleSpecifier).
  • Starts with /.
  • Starts with ./.
  • Starts with ../.
// Supported: 
import {foo} from 'https://myamazingwebsite.com/js/main.js'; 
import {foo} from '/js/main.js';
import {foo} from './main.js';
import {foo} from '../main.js';
// Not supported: 
import {foo} from 'main.js'; 
import {foo} from 'js/main.js';

ES Modules it’s a really important feature, and to build it, from today, will be much simpler.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.