Overview

Getting started with Webpack

No Comments

Initial steps with Webpack can be confusing: Syntax and philosohy are pretty unique, and the documentation is not really beginner-friendly. Another problem I faced when starting to use it: There are many “starter packs” available which provide a build configuration, e.g. for ReactJS, that are very powerful and hard to understand for beginners. So, after working with it in my current project, I decided to help you get started with Webpack, too.

What is Webpack?

Webpack is a module bundler. It allows us to define modules in JavaScript and import them. With webpack you can split your application in multiple, smaller files and import them where needed.

But how do modules work? Let’s first have a look at a small example to gather an understanding of the underlying concepts, before creating a project and implementing the example (you can find the code at GitHub).

First steps on the command line

First we need two JavaScript files where one loads the other to display some content on a webpage.

We create a file add.js which just exports a function that adds two numbers:

module.exports = function(a,b){
  return a+b;
}

Now we need a file which imports this module and writes the content to a webpage. We call this file index.js and save it in the same folder as add.js

var add = require('./add');

document.write("1 + 2 = " + add(1, 2));

We use require to load the file (like we would do in a nodeJS file) and then write the content to the document using document.write.

So how to get this code working in the browser? Create a new file, index.html which just includes the index.js:

<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <script type="text/javascript" src="index.js"></script>
    </body>
</html>

If you open this file in your browser, you get an error: “Uncaught ReferenceError: require is not defined”. We haven’t used Webpack yet, so this is okay. To get our sample working, we need to bundle our JavaScript files into one file.

If you haven’t installed webpack yet, use npm to install it globally:

npm install -g webpack

Afterwards use the command line tool to bundle the JavaScript code:

webpack index.js bundle.js

This command uses index.js as entry point and creates a new file bundle.js as output. The newly generated file combines our two files. Important: It doesn’t concatenate them like you would do it with tools like Gulp or Grunt. If you are curious, have a look at the generated file.

Finally, add bundles.js to our HTML file by replacing index.js with bundle.js. After reloading the HTML file in the browser, the string “1 + 2 = 3” should appear.

This was a first step with Webpack. Let’s have a look at a sample project.

Project setup

First we need a new folder for our project, let’s call it hello-webpack and initialize a new npm project in it (npm init -y creates a project with default values). Then we install Webpack locally:

mkdir hello-webpack
cd hello-webpack
npm init -y
npm install --save webpack

Create a folder src for our JavaScript files and copy index.js and add.js into it. The index.html must be copied into the root folder.

Project structure:

├── index.html
├── node_modules
├── package.json
└── src
    ├── add.js
    └── index.js

To simplify the usage of Webpack here, we can add a configuration file webpack.conf.js which stores all required information:

module.exports = {
    entry: "./src/index.js",
    output: {
        filename: "bundle.js"
    }
};

For our basic sample we only need the entry point: src/index.js and the path to the output: bundle.js. If you execute webpack now, it creates the bundles.js file and everything should work like before.

Adding more modules to Webpack configuration

To be honest, this is a nice example but it doesn’t show why Webpack is so great. Webpack becomes really powerful when you add loaders to it. Let’s start with two pretty useful ones:

  • eslint-loader for linting
  • babel-loader to use modern JavaScript features with the help of Babel

Linting

We use ESLint for linting here. A simple way to add it is by installing eslint, babel-eslint (because we use babel later) and eslint-loader (the loader for Webpack)

npm i eslint babel-eslint eslint-loader --save-dev

Now add a file .eslintrc with our linting configuration to the root of our project:

{
   "parser": "babel-eslint"
}

And finally, tell Webpack that it should use eslint for all JavaScript files:

module.exports = {
    entry: "./src/index.js",
    output: {
        filename: "bundle.js"
    },
    module: {
        preLoaders: [{
            test: /\.js$/,
            loaders: ['eslint'],
        }]
    }
};

The preLoader gets executed on every file which passes the test. In this case, every *.js file. The eslint-loader is executed for those files.

With linting enabled, it is easy to find problematic patterns in our code. Now we can update our modules and use modern JavaScript.

Adding Babel

Again we install a loader via npm. This time babel-loader:

npm i -D babel-loader

Now we can add it to our Webpack configuration:

module.exports = {
    entry: "./src/index.js",
    output: {
        filename: "bundle.js"
    },
    module: {
        preLoaders: [{
            test: /\.js$/,
            loaders: ['eslint'],
        }],
        loader: {
            test: /\.js$/,
            loaders: ['babel']
        }
    }
};

The loader is executed after the preLoader. Like the preLoader it has a test to control which files are handled by the loader.

With Babel in our Webpack configuration, we can use modern JavaScript in our project. Webpack handles bundling and (with help of babel) transpiling of our code.

For example, we can rewrite the file add.js:

module.exports = (a,b) => a+b;

After running Webpack again, the result should be the same as above.

And much more

This was just an introduction to Webpack that showed how to use it to bundle modules and add loaders for linting and transpiling our code. But there is so much more: Webpack is not limited to JavaScript, so you can add other resources like SASS or LESS files or even images to your modules, too. With the help of loaders you can process those files. I’m sure there are many projects where Webpack can replace build tools like Grunt and Gulp.

Comment

Your email address will not be published. Required fields are marked *