Webpack defines itself as a “module bundler.”

What the heck does that mean?

It means less HTTP Get requests in a nutshell.


Node.js, on the backend, allows us to seperate our code into modules to allow easy code reuse and prevent name clashes using CommonJS.


// module1.js
module.exports = {name: "module1"};
// module2.js
module.exports = {name: "module2"};
// app.js
var mod1 = require('module1.js');
var mod2 = require('module2.js');


Unfortunately, CommonJS isn’t supported on the frontend and thus we’re stuck with making several HTTP requests for each piece of code we require.

<script src="one.js"></script>
<script src="two.js"></script>

And even then we’re not guaranteed the order that they’ll load in.

Webpack to the rescue

Webpack takes care of this by bundling all your modules into a single .js file.

Getting started

Create a new package.json using npm:

$ npm init -y

Install webpack locally:

$ npm install --save-dev webpack

Create a file named bundleme.js:

var mod1 = require('./module1');



module.exports = {name: "module1"};

Lastly create an index.html file to load the bundle in the browser:

<!doctype html>
  <script src="bundle.js"></script>

Build it and then open index.html in a browser:

$ ./node_modules/.bin/webpack ./bundleme.js bundle.js

Webpack Build document.write

Note that we installed webpack locally which comes with a prebuilt webpack binary inside the long path above.

Webpack config

Running webpack through the terminal isn’t recommended but instead we can write a config file that configures its options.

Create the file webpack.config.js:

module.exports = {
    entry: "bundleme.js",
    output: {
      path: __dirname,
      filename: "bundle.js"

Add an npm script to package.json that runs webpack:

"scripts": {
    "build": "webpack"    

Now you can run the npm script and your bundle will build:

$ npm run build


Not only can webpack bundle javascript but it can also do .css with loaders.

Install css-loader and style-loader:

$ npm install --save-dev css-loader style-loader

Require a style.css file and pipe it into the loaders:

var mod1 = require('./module1');


Webpack css loader


Webpack comes with helpful plugins such as compressing javascript.

Open webpack.config.js:

var webpack = require('webpack'); 

module.exports = {
    entry: "bundleme.js",
    output: {
      path: __dirname,
      filename: "bundle.js"
    plugins: [
      new webpack.optimize.UglifyJsPlugin()

Run the npm build script and your bundle.js is now minified:

$ npm run build

Webpack plugin uglify

And that’s the basics of Webpack. From here I suggest heading over to the official docs.

Thanks for reading!