In this chapter, we will cover the following recipes:
- Installing and configuring browsers—Chrome and Firefox
- Installing Python, using SimpleHTTPServer to host a local static file server
- Creating an HTML page that loads an ECMAScript module
- Exporting/importing multiple modules for external use
- Renaming imported modules
- Nesting modules under a single namespace
JavaScript is the most famous language that adheres to the ECMAScript standard. This standard was created in the late 1990s in order to guide the development of the language. In the early years, development was slow, with only four major versions reaching production in the first two decades. However, with increased exposure, largely thanks to the popularization of the Node.js run-time, the pace of development has increased dramatically. The years 2015, 2016, and 2017 each saw new releases of the of the standard, with another planned for 2018.
With all these developments, now is an exciting time to be a JavaScript developer. A lot of new ideas are coming in from other languages, and the standard API is expanding to be more helpful. This book focuses on new features and techniques that can be used in the newer versions of JS as well as future versions!
Historically, creating JavaScript programs that span multiple files has been a painful experience. The simplest approach was to include each of the files in separate <script>
tags. This also requires developers to position the tags in the correct order.
Various libraries have attempted to improve this situation. RequireJS, Browserfy, and Webpack all attempt to solve the problem of JavaScript dependencies and module loading. Each of these requires some kind of configuration or build step.
The situation has improved in recent years. Browser manufacturers collaborate in creating the ECMAScript specification. It is then up to the manufacturers to implement JavaScript interpreters (programs that actually run the JavaScript) that adhere to that specification
New versions of browsers are being released that support native ECMAScript modules. ECMAScript modules provide an elegant method for including dependencies. Best of all, unlike the previous methods, modules don't require any build step or configuration.
The recipes in this chapter focus on installing and configuring the Chrome and Firefox web browsers and how to take full advantage of ES modules and the import/export syntax.
Subsequent recipes will assume an environment that is capable of using ES modules. There are two strategies for accomplishing this: creating a build step that collects all the modules used into a single file for the browser to download, or using a browser that is capable of using ES modules. This recipe demonstrates the latter option.
To step through this recipe, you need a computer with an operating system (OS) that is supported by Chrome (not Chromium). It supports recent versions of Windows and macOS, as well as a large number of Linux distributions. Most likely, if your OS doesn't support this browser, you are already aware of this.
- To download Chrome, navigate your browser to the following:https://www.google.co.in/chrome/.
- Click
Download
and accept the terms of service. - After the installer finishes downloading, double-click the installer to launch it and follow the onscreen instructions.
- To check the version of Chrome, open the Chrome browser, and enter the following URL:
chrome://settings/help
. - You should see the
Version
number where the number is 61 or higher. See the following screenshot:
The current versions of Chrome come with ES modules enabled out of the box. So no configuration or plugins are required to get them working!
At the time of writing, only a few browsers support ECMAScript. You can see which browsers support modules under the Browser compatibility
section of the page at https://mzl.la/1PY7nnm.
Subsequent recipes will assume an environment that is capable of using ES modules. There are two strategies for accomplishing this: creating a build step that collects all the modules used into a single file for the browser to download, or using a browser that is capable of using ES modules. This recipe demonstrates the latter option.
To step through this recipe, you need a computer with an operating system (OS) that is supported by Firefox. It supports recent versions of Windows and macOS, as well as a large number of Linux distributions. Most likely, if your OS doesn't support Firefox, you are already aware of this.
- To install Firefox, open a browser and enter the following URL:
https://www.mozilla.org/firefox
. - Click the button that says
Download
to download the installer. - After the installer has finished downloading, double click the installer and follow the onscreen instructions.
- To configure Firefox, open the Firefox browser and enter the following URL:
about:config
. - The menu will allow you to enable advanced and experimental features. If you see a warning, click the button that says
I accept the risk!
- Find the
dom.moduleScripts.enabled
setting, and double-click it to set the value totrue,
as shown in following screenshot:

It is possible to browse web pages directly from the filesystem. However, Chrome and Firefox have security features that make this inconvenient for development. What we need is a simple static file server. This recipe demonstrates how to install Python (if necessary) and use it to serve files from a directory.
Find out how to open the command line on your OS. On macOS and Linux, this is called the Terminal. On Windows, it is called the Command Prompt.
You should use a browser that is configured to load ES modules (see the first recipe).
- Check whether you have Python installed already.
- Open the command line.
- Enter the following command:
python --version
- If you see an output like the one displayed as follows, Python is already installed. And you can skip to step 6:
Python 2.7.10
- If you receive an error such as the following, continue with the installation in step 5:
command not found: python
- Install Python on your computer:
- For macOS, download and run the installer for the latest version of Python 2 or 3 from the following link: https://www.python.org/downloads/mac-osx/
- For Windows, download and run the installer for the latest version of Python 2 or 3 from the following link: https://www.python.org/downloads/windows/
- For Linux, use the operating system's built in the package manager to install the Python package
- Create a folder on your desktop named
es8-cookbook-workspace
. - Inside the folder, create a text file named
hello.txt
and save some text to it. - Open the Command Prompt and navigate to the folder:
- In the Linux or macOS Terminal enter:
cd ~/Desktop/es8-cookbook-workspace
- On Windows type the following command:
cd C:Desktopes8-cookbook-workspace
- Start the Python HTTP server with the following command:
python -m SimpleHTTPServer # python 2
Or we can use following command:
python -m http.server # python 3
- You should see a page that shows the contents of the
es8-cookbook-workspace
folder:

- Click on the link to
hello.txt
and you'll see the text contents of the file you created.
The first thing we did was check if Python was installed. The best way to do this is to ask Python for its version number. This way we know whether Python is installed, and if it's new enough for our purposes.
If it's not installed, Python can be retrieved via the OS's package manager, or via the installers made available through Python's website.
Once installed, Python comes with a lot of utilities. The one we are interested in is the appropriately named SimpleHTTPServer
. This utility listens for HTTP requests on port 8000
, and returns the contents of the files relative to the directory root. If the path points to a directory, it returns an HTML page that lists the directory contents.
In previous recipes, we went over installation and configurations instructions to run a static file server using Python and configure a browser to use ES modules.
This recipe assumes that you have the static file server running in your working directory. If you haven't installed Python or configured your browser to work with ES modules, please see the first two recipes in the book.
The following steps will demonstrate how to create an ES module and load it into an HTML file.
- Create an
hello.html
file with a some text content:
<html> <meta charset="UTF-8" /> <head> </head> <body> Open Your Console! </body> </html>
- Open
hello.html
by opening your browser, and entering the following URL:http://localhost:8000/hello.html
.
- You should see
Open Your Console!
displayed by the browser:
Ctrl + Shift + I
- On macOS:
Cmd + Shift + I
- Next, in the same directory, create a file called
hello.js
, which exports a function namedsayHi
that writes a message to the console:
// hello.js export function sayHi () { console.log('Hello, World'); }
- Next add a script module tag to the head of
hello.html
that imports thesayHi
method fromhello.js
(pay attention to the type value).
- Reload the browser window with the Developer Console open and you should see the
hello
message displayed as text:

Although our browser can work with ES modules, we still need to specify that is how we want our code to be loaded. The older way of including script files uses type="text/javascript"
. This tells the browser to execute the content of the tag immediately (either from tag contents or from the src
attribute).
By specifying type="module"
, we are telling the browser that this tag is an ES module. The code within this tag can import members from other modules. We imported the function sayHi
from the hello
module and executed it within that <script>
tag. We'll dig into the import
and export
syntax in the next couple of recipes.
In the previous recipe, we loaded an ES module into an HTML page and executed an exported function. Now we can take a look at using multiple modules in a program. This allows us more flexibility when organizing our code.
- Create a new working directory, navigate into it with your command-line application, and start the Python
SimpleHTTPServer
. - Create a file named
rocket.js
that exports the name of a rocket, a countdown duration, and a launch function:
export default name = "Saturn V"; export const COUNT_DOWN_DURATION = 10; export function launch () { console.log(`Launching in ${COUNT_DOWN_DURATION}`); launchSequence(); } function launchSequence () { let currCount = COUNT_DOWN_DURATION; const countDownInterval = setInterval(function () { currCount--; if (0 < currCount) { console.log(currCount); } else { console.log('LIFTOFF!!!'); clearInterval(countDownInterval); } }, 1000); }
- Create a file named
main.js
that imports fromrocket.js
, logs out details, and then calls the launch function:
import rocketName, {COUNT_DOWN_DURATION, launch } from './rocket.js'; export function main () { console.log('This is a "%s" rocket', rocketName); console.log('It will launch in "%d" seconds.', COUNT_DOWN_DURATION); launch(); }
- Next, create an
index.html
file that imports themain.js
module and runs themain
function:
<html> <head> <meta charset='UTF-8' /> </head> <body> <h1>Open your console.</h1> <script type="module"> import { main } from './main.js'; main(); </script> </body> </html>

There are two options for exporting a member from a module. It can either be exported as the default
member, or as a named member. In rocket.js
, we see both methods:
export default name = "Saturn V"; export const COUNT_DOWN_DURATION = 10; export function launch () { ... }
In this case, the string "Saturn V"
is exported as the default member, while COUNT_DOWN_DURATION
and launch
are exported as named members. We can see the effect this has had when importing the module in main.js
:
import rocketName, { launch, COUNT_DOWN_DURATION } from './rocket.js';
We can see the difference in how the default member and the name members are imported. The name members appear inside the curly braces, and the name they are imported with matches their name in the module source file. The default module, on the other hand, appears outside the braces, and can be assigned to any name. The unexported member launchSequence
cannot be imported by another module.
Modules allow more flexibility in organizing code. This allows for a shorter, more contextual name. For example, in the previous recipe, we named a function launch
instead of something more verbose such as launchRocket
. This helps keep our code more readable, but it also means that different modules can export members that use the same name.
In this recipe, we'll rename imports in order to avoid these namespace collisions.
We'll be reusing the code from the previous recipe (Exporting/importing multiple modules for external use). The changes from the previous files will be highlighted.
- Copy the folder created for the previous recipe into a new directory.
- Navigate to that directory with your command-line application and start the Python server.
- Rename
rocket.js
tosaturn-v.js
, add the name of the rocket to the log statements, and update themain.js
import statement:
// main.js import name, { launch, COUNT_DOWN_DURATION } from './saturn-v.js'; export function main () { console.log('This is a "%s" rocket', name); console.log('It will launch in "%d" seconds.', COUNT_DOWN_DURATION); launch(); } // saturn-v.js export function launch () { console.log(`Launching %s in ${COUNT_DOWN_DURATION}`, name); launchSequence(); } function launchSequence () { // . . . console.log(%shas LIFTOFF!!!', name); // . . . }
- Copy
saturn-v.js
to a new file namedfalcon-heavy.js
and change the default export value and theCOUNT_DOWN_DURATION
:
export default name = "Falcon Heavy";export const COUNT_DOWN_DURATION = 5;
import rocketName, { launch, COUNT_DOWN_DURATION } from './saturn-v.js'; import falconName, { launch as falconLaunch, COUNT_DOWN_DURATION as falconCount } from './falcon-heavy.js'; export function main () { console.log('This is a "%s" rocket', rocketName); console.log('It will launch in "%d" seconds.', COUNT_DOWN_DURATION); launch(); console.log('This is a "%s" rocket', falconName); console.log('It will launch in "%d" seconds.', falconCount); falconLaunch(); }
- Open
index.html
in your browser and you should see the following output:

When we duplicated the saturn-v.js
file to and imported the members from falcon-heavy.js
, we had a potential namespace conflict. Both files export members named COUNT_DOWN_DURATION
and launch. But using the as
keyword, we renamed those members in order to avoid that conflict. Now the importing main.js
file can use both sets of members without issue.
Renaming members can also be helpful to adding context. For example, it might be useful to rename the launch as launchRocket
even if there is no conflict. This give the importing module additional context, and makes the code a bit clearer.
As the number of modules grows, patterns start to emerge. For practical and architectural reasons, it makes sense to group multiple modules together and use them as a single package.
This recipe demonstrates how to collect multiple modules together and use them as a single package.
It will be helpful to have the source code available from previous recipes to bootstrap this recipe. Otherwise, you'll need to reference Exporting/importing multiple modules for external use for how to create the index.html
file.
- Create a new folder with an
index.html
file, as seen in Exporting/importing multiple modules for external use. - Inside of that directory, create a folder named
rockets
. - Inside of
rockets
, create three files:falcon-heavy.js
,saturn-v.js
, andlaunch-sequence.js
:
// falcon-heavy.js import { launchSequence } from './launch-sequence.js'; export const name = "Falcon Heavy"; export const COUNT_DOWN_DURATION = 5; export function launch () { launchSequence(COUNT_DOWN_DURATION, name); } (COUNT_DOWN_DURATION); } // saturn-v.js import { launchSequence } from './launch-sequence.js'; export const name = "Saturn V"; export const COUNT_DOWN_DURATION = 10; export function launch () { launchSequence(COUNT_DOWN_DURATION, name); } // launch-sequence.js export function launchSequence (countDownDuration, name) { let currCount = countDownDuration; console.log(`Launching in ${COUNT_DOWN_DURATION}`, name); const countDownInterval = setInterval(function () { currCount--; if (0 < currCount) { console.log(currCount); } else { console.log('%s LIFTOFF!!!', name); clearInterval(countDownInterval); } }, 1000); }
- Now create
index.js
, which exports the members of those files:
import * as falconHeavy from './falcon-heavy.js'; import * as saturnV from './saturn-v.js'; export { falconHeavy, saturnV };
import { falconHeavy, saturnV } from './rockets/index.js' export function main () { saturnV.launch(); falconHeavy.launch(); }
- Open in the browser, and see the following output:

The * syntax seen on the first two lines of index.js
imports all the exported members under the same object. This means that the name
, COUNT_DOWN_DURATION
, and launch
members of falcon-heavey.js
are all attached to the falconHeavy
variable. Likewise, for the saturn-v.js
modules and the saturnV
variable. So, when falconHeavy
and saturnV
are exported on line 4, those exported names now contain all the exported members of their respective modules.
This provides a single point where another module (main.js
in this case) can import those members. The pattern has three advantages. It is simple; there is only one file to import members from, rather than many. It is consistent, because all packages can use an index
module to expose members of multiple modules. It is more flexible; members of some modules can be used throughout a package and not be exported by the index
module.
It is possible to export named items directly. Consider the following file, atlas.js
:
import { launchSequence } from './launch-sequence.js'; const name = 'Atlas'; const COUNT_DOWN_DURATION = 20; export const atlas = { name: name, COUNT_DOWN_DURATION: COUNT_DOWN_DURATION, launch: function () { launchSequence(COUNT_DOWN_DURATION, name); } };
The atlas
member can be exported directly by index.js
:
import * as falconHeavy from './falcon-heavy.js';
import * as saturnV from './saturn-v.js';
export { falconHeavy, saturnV };
export { atlas } from './atlas.js';
Then the main.js
file can import the atlas
member and launch it:
import { atlas, falconHeavy, saturnV } from './rockets/index.js' export function main () { saturnV.launch(); falconHeavy.launch(); atlas.launch(); }
This is one benefit of always using named exports; it's easier to collect and export specific members from packages with multiple modules.
Whether named or not, nesting is a great technique for grouping modules. It provides a mechanism for organizing code as the number of modules continues to grow.