Webpack is a tool that has got a lot of attention in the last few years, and it is now seen used in almost every project.

Given its widely used status, you cannot really afford to not know Webpack.


What can Webpack do?

Webpack is a swiss knife for helping you developing and shipping your web application.

It’s a module bundler.

It helps you bundle your resources.

It’s also a CSS, HTML and images task runner.

It watches for changes and re-runs the tasks.

It runs Babel transpilation to ES5, allowing you to use the latest JavaScript features without worrying about browser support.

It can transpile CoffeeScript to JavaScript

It can convert inline images to data URIs.

It allows you to use require() for CSS files.

It can run a development webserver.

It can handle hot code reload.

It can split the output files into multiple files, to avoid having a huge js file to load in the first page hit.

It can perform tree shaking.


Compare Webpack with its competitors

Where does it fit in the grand scheme of things?

Predecessors of Webpack, and still widely used tools, are

  • Grunt
  • Broccoli
  • Gulp

Why is Webpack better than its competitors?

It has a more simple syntax, better support for projects with lots of files, and better integration with other modern tools.


Installing Webpack

Webpack is installed very easily with Yarn:

yarn global add webpack

or with npm:

npm i -g webpack

once this is done, you should be able to run

$ webpack --help
webpack 3.5.6
Usage: https://webpack.js.org/api/cli/
Usage without config file: webpack <entry> [<entry>] <output>
Usage with config file: webpack
...

Webpack configuration

The Webpack configuration is usually stored in a file named webpack.config.js in a project root folder.

This simple example compiles the ./index.js file into output.js

const webpack = require('webpack')

let config = {
  entry = './index.js',
  output: {
    filename: 'output.js'
  }
}

module.exports = config

In the next articles you’ll see some more useful configuration options.


Running Webpack

Webpack can be run from the command line manually, but generally one writes a script inside the package.json file, which is then run using npm or yarn.

For example this package.json scripts definition:

"scripts": {
  "start": "webpack --watch"
},

allows us to run webpack --watch by running

npm start

or

yarn run start

Is Webpack a task runner?

No! Webpack is a module bundler. It relies on npm or yarn as a task runner, like you saw in the example above.