Native ECMAScript directly in browser

In January 2018 Firefox also released <script type="module">, in their nightly builds. This means that developers can use native ECMAScript modules directly in browser without babel,  tranceur or other additional buildsteps and module bundlers like Parcel, Rollup or Webpack.

Chromium based browsers like Opera and Google Chrome have had ES6 Module support since early 2017. The same has Edge (since ver. 16) and Safari since ver. 10.1. Among most popular browsers only the dying Internet Explorer lacks the feaure. This means that approximately 80-85% of browsers in use are more or less ready for native ECMAScript modules and async/wait, classes, arrow functions, fetch, promisis, map, set etc…

If your browser supports <script type="module"> it will also ignore the fallback script block <script nomodule>

Use is plain and simple. When you use type="module" on the script element the browser will treat the inline or external script as an ECMAScript module and will understand and ignore any  nomodule script element.

If the async attribute is present, then the module script and all its dependencies will be fetched in parallel to parsing of the HTML, and the module script will be evaluated as soon as it is available (potentially before parsing completes). Otherwise, the module script and its dependencies will be fetched in parallel to parsing and evaluated when the page has finished parsing.

If you try something like import ‘main.js’ inline, you will receive an error:
Uncaught TypeError: Failed to resolve module specifier "main.js". Relative references must start with either "/", "./", or "../".

So the way to go is either a full non-relative URL or ‘./main.js’

The following two simple modules:

import Greeting from "./utils.js";
let greet = new Greeting('from utils.js');
console.log("Hello from main.js");

export default class Greeting {
	constructor(name) {
		this._name = name;
	sayHey() {
		return `Greetings from ${this._name}`;

… will produce the following output to console:

You will need a basic web server of some sort to run the code as modules aren’t supported by the file protocol.