JavaScript modules

このロケールの翻訳が存在しないため、英語バージョンのコンテンツを表示しています。 Help us translate this article!

This guide gives you all you need to get started with JavaScript module syntax.

A background on modules

JavaScript programs started off pretty small — most of its usage in the early days was to do isolated scripting tasks, providing a bit of interactivity to your web pages where needed, so large scripts were generally not needed. Fast forward a few years and we now have complete applications being run in browsers with a lot of JavaScript, as well as JavaScript being used in other contexts (Node.js, for example).

It has therefore made sense in recent years to start thinking about providing mechanisms for splitting JavaScript programs up into separate modules that can be imported when needed. Node.js has had this ability for a long time, and there are a number of JavaScript libraries and frameworks that enable module usage (for example, other CommonJS and AMD-based module systems like RequireJS, and more recently Webpack and Babel).

The good news is that modern browsers have started to support module functionality natively, and this is what this article is all about. This can only be a good thing — browsers can optimize loading of modules, making it more efficient than having to use a library and do all of that extra client-side processing and extra round trips.

Browser support

Use of native JavaScript modules is dependent on the import and export statements, the browser compatibility of which is as follows:

import

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
importChrome Full support 61Edge Full support 16
Full support 16
Full support 15
Disabled
Disabled From version 15: this feature is behind the Experimental JavaScript Features preference.
Firefox Full support 60
Full support 60
No support 54 — 60
Disabled
Disabled From version 54 until version 60 (exclusive): this feature is behind the dom.moduleScripts.enabled preference. To change preferences in Firefox, visit about:config.
IE No support NoOpera Full support 47Safari Full support 10.1WebView Android Full support 61Chrome Android Full support 61Firefox Android Full support 60
Full support 60
No support 54 — 60
Disabled
Disabled From version 54 until version 60 (exclusive): this feature is behind the dom.moduleScripts.enabled preference. To change preferences in Firefox, visit about:config.
Opera Android Full support 44Safari iOS Full support 10.3Samsung Internet Android Full support 8.0nodejs Full support 8.5.0
Notes Disabled
Full support 8.5.0
Notes Disabled
Notes files must have suffix .mjs, not .js
Disabled From version 8.5.0: this feature is behind the --experimental-modules runtime flag.
Dynamic importChrome Full support 63Edge No support No
Notes
No support No
Notes
Notes See development status.
Firefox Full support 67
Full support 67
No support 66 — 67
Disabled
Disabled From version 66 until version 67 (exclusive): this feature is behind the javascript.options.dynamicImport preference (needs to be set to true). To change preferences in Firefox, visit about:config.
IE No support NoOpera Full support 50Safari Full support 11.1WebView Android Full support 63Chrome Android Full support 63Firefox Android Full support 67
Full support 67
No support 66 — 67
Disabled
Disabled From version 66 until version 67 (exclusive): this feature is behind the javascript.options.dynamicImport preference (needs to be set to true). To change preferences in Firefox, visit about:config.
Opera Android Full support 46Safari iOS Full support 11.3Samsung Internet Android Full support 8.0nodejs ?
Available in workersChrome Full support 80
Full support 80
Full support 67
Disabled
Disabled From version 67: this feature is behind the Experimental Web Platform Features preference. To change preferences in Chrome, visit chrome://flags.
Edge No support NoFirefox No support NoIE No support NoOpera No support NoSafari No support NoWebView Android Full support 80Chrome Android Full support 80
Full support 80
Full support 67
Disabled
Disabled From version 67: this feature is behind the Experimental Web Platform Features preference. To change preferences in Chrome, visit chrome://flags.
Firefox Android No support NoOpera Android No support NoSafari iOS No support NoSamsung Internet Android No support Nonodejs Full support Yes
Full support Yes
Full support Yes
Disabled
Disabled This feature is behind the --enable-experimental-web-platform-features runtime flag.

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.

export

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
exportChrome Full support 61Edge Full support 16
Full support 16
Full support 15
Disabled
Disabled From version 15: this feature is behind the Experimental JavaScript Features preference.
Firefox Full support 60
Full support 60
No support 54 — 60
Disabled
Disabled From version 54 until version 60 (exclusive): this feature is behind the dom.moduleScripts.enabled preference. To change preferences in Firefox, visit about:config.
IE No support NoOpera Full support 47Safari Full support 10.1WebView Android No support NoChrome Android Full support 61Firefox Android Full support 60
Full support 60
No support 54 — 60
Disabled
Disabled From version 54 until version 60 (exclusive): this feature is behind the dom.moduleScripts.enabled preference. To change preferences in Firefox, visit about:config.
Opera Android Full support 44Safari iOS Full support 10.3Samsung Internet Android Full support 8.0nodejs ?

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown
User must explicitly enable this feature.
User must explicitly enable this feature.

Introducing an example

To demonstrate usage of modules, we've created a simple set of examples that you can find on GitHub. These examples demonstrate a simple set of modules that create a <canvas> element on a webpage, and then draw (and report information about) different shapes on the canvas.

These are fairly trivial, but have been kept deliberately simple to demonstrate modules clearly.

Note: If you want to download the examples and run them locally, you'll need to run them through a local web server.

Basic example structure

In our first example (see basic-modules) we have a file structure as follows:

index.html
main.mjs
modules/
    canvas.mjs
    square.mjs

Note: All of the examples in this guide have basically the same structure; the above should start getting pretty familiar.

The modules directory's two modules are described below:

  • canvas.mjs — contains functions related to setting up the canvas:
    • create() — creates a canvas with a specified width and height inside a wrapper <div> with a specified ID, which is itself appended inside a specified parent element. Returns an object containing the canvas's 2D context and the wrapper's ID.
    • createReportList() — creates an unordered list appended inside a specified wrapper element, which can be used to output report data into. Returns the list's ID.
  • square.mjs — contains:
    • name — a constant containing the string 'square'.
    • draw() — draws a square on a specified canvas, with a specified size, position, and color. Returns an object containing the square's size, position, and color.
    • reportArea() — writes a square's area to a specific report list, given its length.
    • reportPerimeter() — writes a square's perimeter to a specific report list, given its length.

Note: In native JavaScript modules, the extension .mjs is important because browsers import the files with a JavaScript compatible MIME-type — text/javascript — using this avoids strict MIME type checking errors like "The server responded with a non-JavaScript MIME type". In addition, the .mjs extension is good for clarity (i.e. this file is a module, and not just regular JavaScript) and for interoperability with other tools. See Google's note for further details.

Exporting module features

The first thing you need to do to get access to module features is export them. This is done using the export statement.

The easiest way to use it is to place it in front of any items you want exported out of the module, for example:

export const name = 'square';

export function draw(ctx, length, x, y, color) {
  ctx.fillStyle = color;
  ctx.fillRect(x, y, length, length);

  return {
    length: length,
    x: x,
    y: y,
    color: color
  };
}

You can export functions, var, let, const, and — as we'll see later — classes. They need to be top-level items; you can't use export inside a function, for example.

A more convenient way of exporting all the items you want to export is to use a single export statement at the end of your module file, followed by a comma-separated list of the features you want to export wrapped in curly braces. For example:

export { name, draw, reportArea, reportPerimeter };

Importing features into your script

Once you've exported some features out of your module, you need to import them into your script to be able to use them. The simplest way to do this is as follows:

import { name, draw, reportArea, reportPerimeter } from './modules/square.mjs';

You use the import statement, followed by a comma-separated list of the features you want to import wrapped in curly braces, followed by the keyword from, followed by the path to the module file — a path relative to the site root, which for our basic-modules example would be /js-examples/modules/basic-modules.

However, we've written the path a bit differently — we are using the dot (.) syntax to mean "the current location", followed by the path beyond that to the file we are trying to find. This is much better than writing out the entire relative path each time, as it is shorter, and it makes the URL portable — the example will still work if you move it to a different location in the site hierarchy.

So for example:

/js-examples/modules/basic-modules/modules/square.mjs

becomes

./modules/square.mjs

You can see such lines in action in main.mjs.

Note: In some module systems, you can omit the file extension and the dot (e.g. '/modules/square'). This doesn't work in native JavaScript modules.

Once you've imported the features into your script, you can use them just like they were defined inside the same file. The following is found in main.mjs, below the import lines:

let myCanvas = create('myCanvas', document.body, 480, 320);
let reportList = createReportList(myCanvas.id);

let square1 = draw(myCanvas.ctx, 50, 50, 100, 'blue');
reportArea(square1.length, reportList);
reportPerimeter(square1.length, reportList);

Applying the module to your HTML

Now we just need to apply the main.mjs module to our HTML page. This is very similar to how we apply a regular script to a page, with a few notable differences.

First of all, you need to include type="module" in the <script> element, to declare this script as a module:

<script type="module" src="main.mjs"></script>

The script into which you import the module features basically acts as the top-level module. If you omit it, Firefox for example gives you an error of "SyntaxError: import declarations may only appear at top level of a module".

You can only use import and export statements inside modules; not regular scripts.

Note: You can also import modules into internal scripts, as long as you include type="module", for example <script type="module"> //include script here </script>.

Other differences between modules and standard scripts

  • You need to pay attention to local testing — if you try to load the HTML file locally (i.e. with a file:// URL), you'll run into CORS errors due to JavaScript module security requirements. You need to do your testing through a server.
  • Also, note that you might get different behavior from sections of script defined inside modules as opposed to in standard scripts. This is because modules use strict mode automatically.
  • There is no need to use the defer attribute (see <script> attributes) when loading a module script; modules are deferred automatically.
  • Last but not least, let's make this clear — module features are imported into the scope of a single script — they aren't available in the global scope. Therefore, you will only be able to access imported features in the script they are imported into, and you won't be able to access them from the JavaScript console, for example. You'll still get syntax errors shown in the DevTools, but you'll not be able to use some of the debugging techniques you might have expected to use.

Default exports versus named exports

The functionality we've exported so far has been comprised of named exports — each item (be it a function, const, etc.) has been referred to by its name upon export, and that name has been used to refer to it on import as well.

There is also a type of export called the default export — this is designed to make it easy to have a default function provided by a module, and also helps JavaScript modules to interoperate with existing CommonJS and AMD module systems (as explained nicely in ES6 In Depth: Modules by Jason Orendorff; search for "Default exports").

Let's look at an example as we explain how it works. In our basic-modules square.mjs you can find a function called randomSquare() that creates a square with a random color, size, and position. We want to export this as our default, so at the bottom of the file we write this:

export default randomSquare;

Note the lack of curly braces.

We could instead prepend export default onto the function and define it as an anonymous function, like this:

export default function(ctx) {
  ...
}

Over in our main.mjs file, we import the default function using this line:

import randomSquare from './modules/square.mjs';

Again, note the lack of curly braces. This is because there is only one default export allowed per module, and we know that randomSquare is it. The above line is basically shorthand for:

import {default as randomSquare} from './modules/square.mjs';

Note: The as syntax for renaming exported items is explained below in the Renaming imports and exports section.

Avoiding naming conflicts

So far, our canvas shape drawing modules seem to be working OK. But what happens if we try to add a module that deals with drawing another shape, like a circle or triangle? These shapes would probably have associated functions like draw(), reportArea(), etc. too; if we tried to import different functions of the same name into the same top-level module file, we'd end up with conflicts and errors.

Fortunately there are a number of ways to get around this. We'll look at these in the following sections.

Renaming imports and exports

Inside your import and export statement's curly braces, you can use the keyword as along with a new feature name, to change the identifying name you will use for a feature inside the top-level module.

So for example, both of the following would do the same job, albeit in a slightly different way:

// inside module.mjs
export {
  function1 as newFunctionName,
  function2 as anotherNewFunctionName
};

// inside main.mjs
import { newFunctionName, anotherNewFunctionName } from './modules/module.mjs';
// inside module.mjs
export { function1, function2 };

// inside main.mjs
import { function1 as newFunctionName,
         function2 as anotherNewFunctionName } from './modules/module.mjs';

Let's look at a real example. In our renaming directory you'll see the same module system as in the previous example, except that we've added circle.mjs and triangle.mjs modules to draw and report on circles and triangles.

Inside each of these modules, we've got features with the same names being exported, and therefore each has the same export statement at the bottom:

export { name, draw, reportArea, reportPerimeter };

When importing these into main.mjs, if we tried to use

import { name, draw, reportArea, reportPerimeter } from './modules/square.mjs';
import { name, draw, reportArea, reportPerimeter } from './modules/circle.mjs';
import { name, draw, reportArea, reportPerimeter } from './modules/triangle.mjs';

The browser would throw an error such as "SyntaxError: redeclaration of import name" (Firefox).

Instead we need to rename the imports so that they are unique:

import { name as squareName,
         draw as drawSquare,
         reportArea as reportSquareArea,
         reportPerimeter as reportSquarePerimeter } from './modules/square.mjs';

import { name as circleName,
         draw as drawCircle,
         reportArea as reportCircleArea,
         reportPerimeter as reportCirclePerimeter } from './modules/circle.mjs';

import { name as triangleName,
        draw as drawTriangle,
        reportArea as reportTriangleArea,
        reportPerimeter as reportTrianglePerimeter } from './modules/triangle.mjs';

Note that you could solve the problem in the module files instead, e.g.

// in square.mjs
export { name as squareName,
         draw as drawSquare,
         reportArea as reportSquareArea,
         reportPerimeter as reportSquarePerimeter };
// in main.mjs
import { squareName, drawSquare, reportSquareArea, reportSquarePerimeter } from './modules/square.mjs';

And it would work just the same. What style you use is up to you, however it arguably makes more sense to leave your module code alone, and make the changes in the imports. This especially makes sense when you are importing from third party modules that you don't have any control over.

Creating a module object

The above method works OK, but it's a little messy and longwinded. An even better solution is to import each module's features inside a module object. The following syntax form does that:

import * as Module from './modules/module.mjs';

This grabs all the exports available inside module.mjs, and makes them available as members of an object Module, effectively giving it its own namespace. So for example:

Module.function1()
Module.function2()
etc.

Again, let's look at a real example. If you go to our module-objects directory, you'll see the same example again, but rewritten to take advantage of this new syntax. In the modules, the exports are all in the following simple form:

export { name, draw, reportArea, reportPerimeter };

The imports on the other hand look like this:

import * as Canvas from './modules/canvas.mjs';

import * as Square from './modules/square.mjs';
import * as Circle from './modules/circle.mjs';
import * as Triangle from './modules/triangle.mjs';

In each case, you can now access the module's imports underneath the specified object name, for example:

let square1 = Square.draw(myCanvas.ctx, 50, 50, 100, 'blue');
Square.reportArea(square1.length, reportList);
Square.reportPerimeter(square1.length, reportList);

So you can now write the code just the same as before (as long as you include the object names where needed), and the imports are much neater.

Modules and classes

As we hinted at earlier, you can also export and import classes; this is another option for avoiding conflicts in your code, and is especially useful if you've already got your module code written in an object-oriented style.

You can see an example of our shape drawing module rewritten with ES classes in our classes directory. As an example, the square.mjs file now contains all its functionality in a single class:

class Square {
  constructor(ctx, listId, length, x, y, color) {
    ...
  }

  draw() {
    ...
  }

  ...
}

which we then export:

export { Square };

Over in main.mjs, we import it like this:

import { Square } from './modules/square.mjs';

And then use the class to draw our square:

let square1 = new Square(myCanvas.ctx, myCanvas.listId, 50, 50, 100, 'blue');
square1.draw();
square1.reportArea();
square1.reportPerimeter();

Aggregating modules

There will be times where you'll want to aggregate modules together. You might have multiple levels of dependencies, where you want to simplify things, combining several submodules into one parent module. This is possible using export syntax of the following forms in the parent module:

export * from 'x.mjs'
export { name } from 'x.mjs'

For an example, see our module-aggregation directory. In this example (based on our earlier classes example) we've got an extra module called shapes.mjs, which aggregates all the functionality from circle.mjs, square.mjs, and triangle.mjs together. We've also moved our submodules inside a subdirectory inside the modules directory called shapes. So the module structure in this example is:

modules/
  canvas.mjs
  shapes.mjs
  shapes/
    circle.mjs
    square.mjs
    triangle.mjs

In each of the submodules, the export is of the same form, e.g.

export { Square };

Next up comes the aggregation part. Inside shapes.mjs, we include the following lines:

export { Square } from './shapes/square.mjs';
export { Triangle } from './shapes/triangle.mjs';
export { Circle } from './shapes/circle.mjs';

These grab the exports from the individual submodules and effectively make them available from the shapes.mjs module.

Note: The exports referenced in shapes.mjs basically get redirected through the file and don't really exist there, so you won't be able to write any useful related code inside the same file.

So now in the main.mjs file, we can get access to all three module classes by replacing

import { Square } from './modules/square.mjs';
import { Circle } from './modules/circle.mjs';
import { Triangle } from './modules/triangle.mjs';

with the following single line:

import { Square, Circle, Triangle } from './modules/shapes.mjs';

Dynamic module loading

The newest part of the JavaScript modules functionality to be available in browsers is dynamic module loading. This allows you to dynamically load modules only when they are needed, rather than having to load everything up front. This has some obvious performance advantages; let's read on and see how it works.

This new functionality allows you to call import() as a function, passing it the path to the module as a parameter. It returns a promise, which fulfills with a module object (see Creating a module object) giving you access to that object's exports, e.g.

import('./modules/myModule.mjs')
  .then((module) => {
    // Do something with the module.
  });

Let's look at an example. In the dynamic-module-imports directory we've got another example based on our classes example. This time however we are not drawing anything on the canvas when the example loads. Instead, we include three buttons — "Circle", "Square", and "Triangle" — that, when pressed, dynamically load the required module and then use it to draw the associated shape.

In this example we've only made changes to our index.html and main.js files — the module exports remain the same as before.

Over in main.mjs we've grabbed a reference to each button using a document.querySelector() call, for example:

let squareBtn = document.querySelector('.square');

We then attach an event listener to each button so that when pressed, the relevant module is dynamically loaded and used to draw the shape:

squareBtn.addEventListener('click', () => {
  import('./modules/square.mjs').then((Module) => {
    let square1 = new Module.Square(myCanvas.ctx, myCanvas.listId, 50, 50, 100, 'blue');
    square1.draw();
    square1.reportArea();
    square1.reportPerimeter();
  })
});

Note that, because the promise fulfillment returns a module object, the class is then made a subfeature of the object, hence we now need to access the constructor with Module. prepended to it, e.g. Module.Square( ... ).

Troubleshooting

Here are a few tips that may help you if you are having trouble getting your modules to work. Feel free to add to the list if you discover more!

  • We mentioned this before, but to reiterate: .mjs files need to be loaded with a MIME-type of javascript/esm (or another JavaScript-compatible MIME-type such as application/javascript), otherwise you'll get a strict MIME type checking error like "The server responded with a non-JavaScript MIME type".
  • If you try to load the HTML file locally (i.e. with a file:// URL), you'll run into CORS errors due to JavaScript module security requirements. You need to do your testing through a server. GitHub pages is ideal as it also serves .mjs files with the correct MIME type.
  • Because .mjs is a fairly new file extension, some operating systems might not recognise it, or try to replace it with something else. For example, we found that macOS was silently adding on .js to the end of our .mjs files and then automatically hiding the file extension. So all of our files were actually coming out as x.mjs.js. Once we turned off automatically hiding file extensions, and trained it to accept .mjs, it was OK.

See also