Getting started with webpack - Part 2: Configuration and modules
You will need Node 6.11.5+ installed on your machine.
In the previous part of the series, we learned the very basics of webpack and how we can use it to bundle JavaScript files. We also learned how to use webpack to watch for file changes and bundle when changes are detected.
In this part of the series, we will dig deeper into webpack and see what else is possible. Let’s get started.
Source code for the application is available on GitHub.
Prerequisites
To follow along in this series, you need the following requirements:
- Completed all previous parts of the series.
- Basic knowledge of JavaScript.
- Basic knowledge of the CLI.
- A text editor. VS Code is recommended.
- Node.js (>=6.11.5) and npm installed locally.
Let’s continue with the series.
Configuring webpack
In the first part of the series, we did not have to configure webpack, we just installed it using npm and started using it. However, webpack requires a configuration file and if it does not find one in your project directory, it will use the one it comes bundled with.
The webpack configuration file contains many options and you can use these options to configure webpack to your liking. You can specify the entry points, output points, minification options, and more.
To create a webpack configuration file, create a webpack.config.js
file in the root of the project. If you still have the project we created in the first part of the series, we will be using that. If you don’t have it, you can download it from the GitHub repository.
Now create a new webpack.config.js
file in the project root. By default, webpack will look for this file in the root of your application. However, you can use whatever file name you want and instruct webpack on where to find the configuration file using the following command:
$ webpack --config "/path/to/webpack.config.js"
If you don’t have webpack installed globally, you’ll need to add
npx
ornode_modules/.bin
before the command as stated in the first part of the series.
Open the webpack.config.js
file and paste the following code:
// File: ./webpack.config.js
const webpack = require('webpack')
module.exports = {
// Insert the configuration here
}
This is the base for the configuration and we will typically add our configuration options to the exports object above. Let’s start by telling webpack our input file and output file:
In the exports object, add the following:
// File: ./webpack.config.js
const webpack = require('webpack')
const path = require('path')
module.exports = {
mode: 'development',
entry: path.resolve(__dirname + '/src/index.js'),
output: {
path: path.resolve(__dirname + '/dist/assets'),
filename: 'bundle.js'
}
}
We use
__dirname
andpath.resolve
here to get the absolute path to the current file. Webpack requires absolute paths when specifying thepath
to a file.
Above, we have specified the entry point for webpack and also we have specified the output path and filename. This will make sure webpack starts compiling at the src/index.js
file and outputs to the specified path and file. We also specified the mode
webpack should run in as development
. Other valid values for mode
are production
and none
.
Now that we have this minor configuration, let’s see if it’ll bundle our application as specified. Open the package.json
file and replace the scripts
with the following:
// File: ./package.json
{
// [...]
"scripts": {
"build": "webpack",
"watch": "npm run build -- --watch"
},
// [...]
}
Above, we have removed the CLI options that specified the entry, output, and mode for webpack and we left just the webpack
command. We can do this because we have configured the entry, output, and mode in the webpack.config.js
file.
Now let’s update the ./src/index.js
file to see if our changes will take effect. Replace the contents of the file with the following:
// File: ./src/index.js
document.addEventListener('DOMContentLoaded', function () {
window.setTimeout(function () {
document.getElementsByTagName('h1')[0].innerHTML = 'Hello there sport'
}, 1000);
});
Now, if you have not already, run the command below to install the dependencies:
$ npm install
After installation is complete, run the following command to compile the scripts:
$ npm run build
If all goes well, you should see that there is a new ./dist/assets/bundle.js
file in the project as configured in the configuration file.
There is a lot more to configure when it comes to webpack, you can read more in the documentation here.
Understanding ES6 modules
While working with webpack, you will likely be doing a lot of module import
ing. So let’s see what modules are and how you can use them to make your JavaScript files modular.
JavaScript has had modules for a while but it was implemented via libraries. ES6 is the first time it was introduced as a built-in feature. Modules are essentially files that export some functionality that can then be reused in other places in your code.
Let’s see an example of what a module is. In this example JavaScript file, let’s define a function that generates random characters:
// random.js
function randomNumbers(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
The function above is simple enough, you give it a min
number and max
number and it’ll return a random number from the min
to the max
.
Named module exports
To make the module export this function so it is available to other files we have to export
it by adding the export
keyword before the function
keyword like this:
// random.js
export function randomNumbers(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
After the function in your module has been exported, you can now import
it in other JavaScript files and use the randomNumbers
function. For example:
// main.js
// Imports the function from the module
import { randomNumbers } from './random.js';
// Displays a random number between 100 and 10000
console.log(randomNumbers(100, 10000));
Multiple named module exports
There are other ways to import and export. Above, we made named exports. Named exports have to be imported with the name that they were exported with. You can have multiple named exports in a single file, for example:
// random.js
// First named export
export function randomNumbers(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Second named export
export function randomString() {
function randStr(){
return Math.random().toString(36).substring(2, 15)
}
return randStr() + randStr();
}
Above, we can see that we added a new export randomString
to our previous example and now we have two named exports in this module. We can import
and use them as shown below:
// main.js
// Imports the function from the module
import { randomNumbers, randomString } from './random.js';
// Displays a random number between 100 and 10000
console.log(randomNumbers(100, 10000));
// Displays a random string
console.log(randomString());
As seen above, we imported both the randomNumbers
and randomString
functions from the module and after that, we used it in the current file.
We can also import all available exports in a module in one go like this:
// main.js
// Imports the function from the module
import * as generate from './random.js';
// Displays a random number between 100 and 10000
console.log(generate.randomNumbers(100, 10000));
// Displays a random string
console.log(generate.randomString());
Above, we have imported all the available exports by using the *
wildcard. We also specified an alias object generate
to store all the exports. This alias can be any word you want. Using this method, however, is not encouraged. You should import modules you need one by one when possible. This helps to keep the file size smaller and also makes it so you compile only what you use.
Default module exports
Generally, it’s always a good idea for your modules to have a single responsibility. In this case, we can have a default export in the module. It will look something like this:
// random.js
export default function (min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
As seen above, we have added the default
keyword after the export
keyword. We also removed the function’s name.
Now we can import the module like this:
// main.js
// Imports the function from the module
import generateRandomNumbers from './random.js';
// Displays a random number between 100 and 10000
console.log(generateRandomNumbers(100, 10000));
As seen above, instead of importing any named export, we can define an arbitrary name for the default export when we are importing it.
Note that ES6 imports have to be top-level, therefore, you can’t conditionally import a module using an
if
statement.
Using ES6 modules in our code
Let’s see how we can use modules in our code. Assuming you still have the code from part one, we will use that as the base.
Create a new file src/utilities/random.js
and paste the following code:
// File: ./src/utilities/random.js
export default function() {
function randStr() {
return Math.random()
.toString(36)
.substring(2, 15)
}
return randStr() + randStr();
}
Next, open the src/index.js
file and replace the content with the following code:
// File: src/index.js
import generateRandomString from './utilities/random';
document.addEventListener('DOMContentLoaded', function () {
var randomString = 'Random String: ' + generateRandomString();
window.setTimeout(function () {
document.getElementsByTagName('h1')[0].innerHTML = randomString
}, 0);
});
Now, let’s build the application. Run the command below to compile our code using webpack:
$ npm run build
When the build is complete, open the dist/index.html
and replace the bundle.js
script URL with assets/bundle.js
:
<!-- File: dist/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Webpack Sample</title>
</head>
<body>
<h1>Hello</h1>
<script src="./assets/bundle.js"></script>
</body>
</html>
Then open the dist/server.js
and replace the contents with the following:
// File: ./dist/server.js
const express = require('express');
const app = express();
const port = 3000;
const path = require('path');
app.get('/assets/bundle.js', (req, res) => (
res.sendFile(path.join(__dirname + '/assets/bundle.js'))
));
app.get('/', (req, res) => (
res.sendFile(path.join(__dirname + '/index.html'))
));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
Now you can run the following code to launch our Node.js server:
$ node dist/server.js
Now when you visit http://localhost:3000 on your browser, you should see the application run as seen above.
Conclusion
In this tutorial of the series, we have learned how to configure webpack and define some defaults. We also learned how modules work in ES6. However, webpack is a lot more powerful than this. We will dive a little deeper in the next part.
The source code to this application is available on GitHub.
6 February 2019
by Neo Ighodaro