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.
npm init
does and what package.json
isSomeone 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!
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.
Take a couple minutes to introduce yourself to what npm is through this article.
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
This tutorial covers the package.json
file, which you can use to manage your project’s dependencies
If you run into trouble at any point you can check out the official docs page for more tutorials and documentation.
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 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.
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
.
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.
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.
Webpack Crash Course by Traversy Media (YouTube video 35′ ) Student Approved Resource
Check out the ES6 Modules section on this post to quickly go through the ES6 modules once more.
If you want to dive more into Webpack you can watch this video by Tara Ojo
.