Menu

React, etc. Tech Stack

React, Flux, GraphQL, Hack, HHVM...? All of this and more!

Native JavaScript (ES6) Modules land in Firefox nightly

JavaScript was designed originally in 1995 as a simple scripting language to provide interactivity for web pages. The language never specified a native module system, until the release of the ES2015 (AKA ES7) specification. Now they've made their way to the Firefox browser.

Over the years the JavaScript landscape has had multiple module systems. AMD, CommonJS and SystemJS are some examples of how the community has built modular code. This has created somewhat of a hectic environment for JavaScript developers.

Before 2015 the Node.js project, a server side implementation of JavaScript, popularised CommonJS and the NPM ecosystem. The CommonJS format has become the most commonly adopted module format for JavaScript developers, but it is not supported natively by browsers.

Fast forward some years from the official JavaScript module specification, and now In 2018 they are becoming usable directly in the browser. Chromium based browsers like Opera and Google Chrome have had ES6 Module support for some time.

In January 2018 the Firefox also released the feature in their nightly builds: Enable <script type="module"> in nightly builds. This means that developers will soon be use ES6 modules natively without additional buildsteps and module bundlers like Rollup or Webpack.

Example of JavaScript Module usage in browser

Using the now familiar export and import commands used in React.js and other contemporary JavaScript framework development. Users can create a file (lib.js) and define the exported functions, classes or variables:

function getJSON(url, callback) {
  let xhr = new XMLHttpRequest();
  xhr.onload = function () { 
    callback(this.responseText) 
  };
  xhr.open('GET', url, true);
  xhr.send();
}

export function getUsefulContents(url, callback) {
  getJSON(url, data => callback(JSON.parse(data)));
}

The exported function getUsefulContents can then be imported in the application (app.js) as library code:

import { getUsefulContents } from '/modules/file.js';

getUsefulContents('http://www.example.com',
    data => { doSomethingUseful(data); });

Together with this capability and the HTTP/2 overhead reductions make up for an interesting opportunity for developers to continue working with JavaScript in fragments of code rather than monolithic bundle files created using development tools.

For Node.js developers there is work ongoing to bring native ES6 modules to the server runtime, but there are some challenges with regards to backwards compatibility, which is why the project has for now opted for a separate file suffix (.mjs) for JavaScript modules.

Written by Jorgé on Thursday January 11, 2018

Permalink -

« Next.js vs Nuxt.js - Benchmarks show Spectre patch slows iPhone JavaScript performance by 40% »