Setting Up Webpack With ES6 Modules

Webpack is a module bundler that basically allows you to create a variety of different JavaScript files (modules) and then bundle them into a single JavaScript file that runs in the browser. People who use React are familiar with Webpack through its installation in Create React App, but it’s also a useful tool in non-React projects.

In this tutorial, which has been adopted from this excellent video walkthrough by Ryan Christiani, I’m going to describe the basic installation of Webpack and a simple use of it in action.

After a project is setup with an index.html file, the first thing necessary is to run:

npm init

This will install a package.json file that will store future dependencies.

If you don’t have webpack on your computer and plan on using it in the future, then it’s best to install globally.

npm install — global webpack

(you might need to run “sudo npm install — global webpack” if you get an administrator error)

This way, when it’s needed in the future all we have to do is run the following command from the project directory and it will be automatically loaded into the project:

npm install — save-dev webpack

In the file structure of this project there is an src folder. Within that folder there is an app.js file and a modules folder with a header.js file.

I’ve gone into the app.js file and imported header.js

import header from ‘./modules/header’;

document.body.innerHTML = header;

You’ll notice that a file named webpack.config.js has also been manually created. The next step is to go into this file and setup the configuration of how webpack will compile the content.

In this example, ‘entry’ is the entry point of the application where webpack will begin the compilation. ‘path’ defines the path to where the compiled modules will go and ‘filename’ is the specific file name within that path.

In the past it would be necessary to install Babel to transpile the ES6 modules (and it probably still should be installed for legacy browsers and other features), but ES6 modules have wide support now, so in this instance it’s unnecessary.

Finally, we go into the terminal and enter:

webpack

This will compile the modules and display them on the browser. As you can see, webpack has compiled the modules into the bundle.js file:

And now on the browser we can see the output of the compiled modules. In this instance, all we have is header.js, which looks like: