ES6 Modules Copy

Introduction

Modules is a feature that arrived with ES6. This feature isn’t fully supported by all modern browsers but it is slowly improving. Until then we can make it work using an external module bundler. ES6 modules are starting to appear in many code bases around the net and getting them up and running will give us a chance to explore some new parts of the JavaScript ecosystem.

In this topic we are going to cover much more than the new module syntax. Before we can really use these modules we’re going to have to learn about npm and webpack. Both of these concepts are really important beyond this topic. Since, the modules themselves are simple to implement we are going to learn about a few other things.

Learning Objectives

  • What npm is and where it was commonly used before being adopted on the frontend
  • What npm init does and what package.json is
  • How to install packages using npm
  • What a JavaScript module bundler like webpack is
  • What the concepts "entry" and "output" mean as relates to webpack
  • What a development dependency is
  • What "transpiling code" means and how it relates to frontend development
  • What a task runner is and how it’s used in frontend development
  • How to write an npm automation script
  • The main benefits of writing code in modules
  • What "named exports" and "default exports" are

The History of JavaScript

Someone would wonder why we need or want this stuff. Or what we will gain from all of this added complexity. These are good thoughts and the rest of this topic will give the answers. So let’s get started!

  • Read this article for a bit of a history lesson. It’s long, but it puts what we’re doing here in great perspective. You don’t have to code along with the examples – the tutorials we cover later will go through basically the same process. But it’s good practice and going through the same process multiple times will help it stick faster.
  • Seriously.. spend some time with that article – it really clarifies the ‘WHY’ of the rest of this lesson. [Estimated reading time: 30~45 minutes]

npm

The node package manager is a command line tool that gives you access to a gigantic repository of plugins, libraries and tools. In our Fundamentals course, you will probably have encountered it when you installed the Jasmine testing framework to do our exercises.

  1. Take a couple minutes to introduce yourself to what npm is through this article.

  2. Read this article about Downloading and Installing npm packages locally. At the end of the article you’ll find the next video that teaches you how to install packages with npm:

Duration: 4 minutes

  1. This tutorial covers the package.json file, which you can use to manage your project’s dependencies

  2. If you run into trouble at any point you can check out the official docs page for more tutorials and documentation.

Yarn?

Yarn is a replacement for the default npm. Although it has a few more features than npm, for the most part it does the same thing. Recent versions of npm have incorporated some of the best features of Yarn, so using it won’t offer you any real advantages at this point. Having said that it is a fine project, and maybe worth your consideration later on.

Webpack

Webpack

Webpack is simply a tool for bundling modules. Although webpack is difficult and complex to set it up and use, our needs are few and thus the setup is simple enough. You can see an example of getting it up and running on the front page of their website.

Webpack is a very powerful tool. However with that power comes a decent amount of complexity. Take a look at the sample config file on this page 😱. Don’t let it scare you off! The basic configuration is not difficult and proficiency with webpack looks great on resumes.

Let’s get started with the official documentation.

  1. Code along with the first four steps of this tutorial ("Basic Setup" through "Using a Configuration")

So first we install webpack using npm and then we set up a simple project that requires an external library (lodash – check it out here if it’s new to you) using a simple script tag. Then the site lists a few reasons why this is probably not ideal and lastly moves on using webpack to accomplish the same thing.

There are a couple of key concepts in order to understand how webpack works – entry and output. In this example, we rearranged the files into a src and dist folder. It doesn’t matter how we call those folders but those names are typical. src is our source directory. To be more specific, src is where we write all of the code that webpack is going to bundle up for us. When webpack runs, it goes through all of our files looking for any import statements. Then compiles all of the code we need to run our site into a single file inside of the dist folder (short for distribution). Our entry file is the main application file. This file links (either directly or indirectly) to all of the other modules in our project. In this example, it is /src/index.js. The output file is the compiled version – dist/main.js.

  • For more details browse this document. We will talk about plugins and loaders in another topic.

ES6 Modules

Now it is time to discuss the module syntax. There are only 2 components to it – import and export.

The import statement is the same thing that you used during the webpack tutorial! These things are simple to use.

// a file called firstFunction.js
const firstFunction = () => console.log('THIS IS MY FIRST FUNCTION!')

export { firstFunction }
// another JS file
import { firstFunction } from './firstFunction'

firstFunction() //this should work as expected!

Writing code in modules has many benefits. One of the most compelling is code reuse. For example, let’s say you have written some functions that manipulate the DOM in a specific way. Thus putting all of those functions into their own file as a ‘module’ means that you can copy that file and re-use it very easily.

In addition other benefits include all of the benefits to wrapping your code in factory functions or using the module pattern. Be careful that the module pattern and ES6 modules are not the same things.. this naming convention is frustrating. By using ES6 modules you can keep different parts of your code cleanly separated. This makes writing and maintaining your code much easier and less error-prone. You can definitely export constructors, classes and factory functions from your modules.

Now let’s write a simple module and then we will include it in our code. We are going to continue from where the webpack tutorial left off.

Before beginning your file directory should look something like this:

├── dist
│   ├── main.js
│   └── index.html
├── src
│   └── index.js
├── package-lock.json
├── package.json
└── webpack.config.js

and you should be able to bundle and run webpack by simply typing npx webpack in the terminal.

Add a new file to the src directory called myCountry.js with the following contents:

const myCountry = (country) => 'Hello! I live in ' + country;

export default myCountry

and then in src/index.js import and use your new function.

// import your function
import myCountry from './myCountry';

function component() {
  const myElement = document.createElement('div');

  // use your function!
  myElement.innerHTML = myCountry('Greece');
  return myElement;
}

document.body.appendChild(component());

If you run npx webpack in your project directory your page should show our new function being used.

There are 2 different ways to use exports in your code. The first one is named exports and the second one default exports. Which option you use depends on what you’re exporting. In general if you want to export multiple functions use named exports with this pattern:

const firstFunction = () => 'FIRST FUNCTION'
const secondFunction = () => 'SECOND FUNCTION'

export {
  firstFunction,
  secondFunction
}

and to import them:

import {firstFunction, secondFunction} from './myModule'

This pattern is useful because it gives you the freedom to only import the functions you need in the various files of your program. So if you only need to import the firstFunction it’s perfectly fine.

Additional Resources

In this section you can find a lot of helpful links to other content. This is a supplemental material for you if you want to dive deeper into some concepts.

Leave a Reply