Yes, ES6 module support is finally catching up in browsers, and its almost there in all browsers. Surprisingly Edge got it up and running before Firefox! But even Firefox has it behind a feature flag (check
about:config) and this will be there by default in the next major release.
I’ll not attempt to explain ES6 modules to you. That has already been done in detail here by Ponyfoo and in way more detail here. We’ll just look through how to directly use them in the browser today. If you are looking to just work with ES6 modules in dev mode and serve a transpiled version of it to the client, here is a good article by Scott Vinkle.
Load up that those script tags!
Use script type as
module and you are all set! Just a couple of things to keep in mind though.
Scripts of type module are deferred by default. But you can override that behaviour with making them async. (Psst, confused between deferred and async again? Here you go.)
OK, so you added a module type script tag to your html and fired it up in the browser to test. But oops…, instead you are greeted with
CORS & Mime type
Unlike regular scripts, module scripts (and their imports) are fetched with CORS. This means cross-origin module scripts have to return valid CORS headers (such as
Access-Control-Allow-Origin: * ).
So you cannot test module type scripts by opening the html file directly in the browser. You need a server serving them with the required CORS headers.
So, you setup a basic node server (express to the rescue!). and start up the app.
But as soon as you go to
localhost:8080, you get-
That is because modules must be served with the MIME type
server code fixes this issue and ES6 modules now run smoothly! Go wild!
You may not be able to use ES6 modules directly for your professional work right now, but that shouldn’t stop you from using them in your code and transpiling it for all browsers. ES6 modules are the future.
In NodeJS too, we were already able to use ES6 modules with a
.js extension were still defaulting to CommonJS. But from v10 (which is out now!) Node will be supporting it fully and it will not need a separate extension.
Please feel free to leave a response or tweet me with any questions or suggestions.