Webpack from Nothing

WTF is a Webpack

Webpack is becoming the standard in bundling JavaScript, but what does that even mean and how does it work? Let's find out.

I find the configuration of Webpack hard to understand and derive. I find the general concept of Webpack very difficult to grasp, especially when reading the myriad blogs documenting the way to set it up—they are all different!

The source of these problems is that Webpack is a monolithic system that does many unrelated things in an opaque way, while also being designed around extreme flexibility. Unlike a monolithic framework such as Ruby on Rails, nothing in Webpack “just works”—you have to provide configuration for Webpack's most basic features to work.

This is part of JavaScript's culture—each new problem in your development environment is viewed as a chance to invent a solution from first principles and no particular opinion on this is viewed as canonical or idiomatic. This means we'll be spending a lot of time in documentation and a lot of time making decisions that have nothing to do with our users or the problems we're trying to solve for them.

So, let's figure out what even is a Webpack together by starting from nothing. You'll be amazed at how little JSON you need to throw at this problem, Medium blog posts be damned!

What Problem Does Webpack Solve?

Webpack exists to give us a feature of JavaScript that exists in most other languages by default - modularization.

As programmers, we want to put code in different files for the purposes of organization. Said another way, we don't want all our JavaScript in one file. We may also wish to use third-party JavaScript libraries to help us.

Because JavaScript fails to meet many programmer's needs, there has always been a requirement to have some sort of way to deploy code organized in multiple files to a user's web browser.

The simplest way is to use a <script> tag for each file:

<script src="js/main.js"></script>
<script src="js/address.js"></script>
<script src="js/billing.js"></script>

This is hard to maintain, so another way is to concatenate all the files together into one bundle during the build of your application, and deploy just that bundle to the user's browser.

> find js -name \*.js \
          -exec cat {} \; >> bundle.js
<script src="bundle.js"></script>

This is what the Rails Asset Pipeline effectively does.

This is not good enough for many reasons:

If only JavaScript had a module system like every other language. It sorta does, but not in any useful way, because no browser supports the latest version of JavaScript. And no browser ever will (since “the latest version of JavaScript“ is a moving target).

Webpack implements a module system as well as a way to translate JavaScript code that doesn't work in any web browser to JavaScript code that works in most web browsers. It's like a C compiler.

It allows you to write code like this, which is remedial in most other modern languages:

// inside main.js
import address from "address";
import billing from "billing";

billing.some_function();
address.some_other_function();

Webpack allows you to specify that main.js is your main file, and that main.js might contain instructions for locating other files, which Webpack should do, recursively until all needed files have been located. All those files should then be brought together and translated into a single file, suitable for use in a web browser.

Surprisingly, webpack *.js > bundle.js does not do this. Because the JavaScript ecosystem favors monolithic, do-everything tools, Webpack, in fact, does everything (except what it doesn't—we'll get to that). It's super flexible, which means it's hard to use, hard to understand, and hard to learn.

I'm going to try to correct that by starting from a very simple case, and building things up, one step at a time, until we have a reasonable development and production environment, while only adding configuration when there is a problem that needs solving.

Webpack from First Principles

To install Webpack, you'll need Node, so go install it (you might want to use a package manager). You'll need need a JavaScript library downloader, which used to be only NPM, but now you should use Yarn, so go install it.

Many tutorials and READMEs tell you to install JavaScript packages willy-nilly. We aren't going to do that. We're going to have a file to keep track of all the stuff our project needs. That file is package.json and Yarn can create one for us. This allows us to recreate our system whenever we want without having to re-execute a bunch of commands.

> yarn -y init
yarn init v1.3.2
success Saved package.json
Done in 0.04s.
warning The yes flag has been set. This will automatically answer yes to all questions which may have security implications.

This will create an empty package.json for us. Now, let's install Webpack!

> yarn add webpack
yarn add v1.3.2
info No lockfile found.
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 313 new dependencies.
├─ abbrev@1.1.1
├─ acorn-dynamic-import@2.0.2
├─ acorn@5.2.1
├─ ajv-keywords@2.1.1
├─ ajv@5.3.0
├─ align-text@0.1.4
├─ ansi-regex@2.1.1
├─ anymatch@1.3.2
├─ aproba@1.2.0
├─ are-we-there-yet@1.1.4
├─ arr-diff@2.0.0
├─ arr-flatten@1.1.0
├─ array-unique@0.2.1
├─ asn1.js@4.9.2
├─ asn1@0.2.3
├─ assert-plus@1.0.0
├─ assert@1.4.1
├─ async-each@1.0.1
├─ async@2.6.0
├─ asynckit@0.4.0
├─ aws-sign2@0.6.0
├─ aws4@1.6.0
├─ balanced-match@1.0.0
├─ base64-js@1.2.1
├─ bcrypt-pbkdf@1.0.1
├─ big.js@3.2.0
├─ binary-extensions@1.10.0
├─ block-stream@0.0.9
├─ bn.js@4.11.8
├─ boom@2.10.1
├─ brace-expansion@1.1.8
├─ braces@1.8.5
├─ brorand@1.1.0
├─ browserify-aes@1.1.1
├─ browserify-cipher@1.0.0
├─ browserify-des@1.0.0
├─ browserify-rsa@4.0.1
├─ browserify-sign@4.0.4
├─ browserify-zlib@0.1.4
├─ buffer-xor@1.0.3
├─ buffer@4.9.1
├─ builtin-modules@1.1.1
├─ builtin-status-codes@3.0.0
├─ camelcase@4.1.0
├─ caseless@0.12.0
├─ center-align@0.1.3
├─ chokidar@1.7.0
├─ cipher-base@1.0.4
├─ cliui@3.2.0
├─ co@4.6.0
├─ code-point-at@1.1.0
├─ combined-stream@1.0.5
├─ concat-map@0.0.1
├─ console-browserify@1.1.0
├─ console-control-strings@1.1.0
├─ constants-browserify@1.0.0
├─ core-util-is@1.0.2
├─ create-ecdh@4.0.0
├─ create-hash@1.1.3
├─ create-hmac@1.1.6
├─ cross-spawn@5.1.0
├─ cryptiles@2.0.5
├─ crypto-browserify@3.12.0
├─ d@1.0.0
├─ dashdash@1.14.1
├─ date-now@0.1.4
├─ debug@2.6.9
├─ decamelize@1.2.0
├─ deep-extend@0.4.2
├─ delayed-stream@1.0.0
├─ delegates@1.0.0
├─ des.js@1.0.0
├─ detect-libc@1.0.2
├─ diffie-hellman@5.0.2
├─ domain-browser@1.1.7
├─ ecc-jsbn@0.1.1
├─ elliptic@6.4.0
├─ emojis-list@2.1.0
├─ enhanced-resolve@3.4.1
├─ errno@0.1.4
├─ error-ex@1.3.1
├─ es5-ext@0.10.35
├─ es6-iterator@2.0.3
├─ es6-map@0.1.5
├─ es6-set@0.1.5
├─ es6-symbol@3.1.1
├─ es6-weak-map@2.0.2
├─ escope@3.6.0
├─ esrecurse@4.2.0
├─ estraverse@4.2.0
├─ event-emitter@0.3.5
├─ events@1.1.1
├─ evp_bytestokey@1.0.3
├─ execa@0.7.0
├─ expand-brackets@0.1.5
├─ expand-range@1.8.2
├─ extend@3.0.1
├─ extglob@0.3.2
├─ extsprintf@1.3.0
├─ fast-deep-equal@1.0.0
├─ fast-json-stable-stringify@2.0.0
├─ filename-regex@2.0.1
├─ fill-range@2.2.3
├─ find-up@2.1.0
├─ for-in@1.0.2
├─ for-own@0.1.5
├─ forever-agent@0.6.1
├─ form-data@2.1.4
├─ fs.realpath@1.0.0
├─ fsevents@1.1.2
├─ fstream-ignore@1.0.5
├─ fstream@1.0.11
├─ gauge@2.7.4
├─ get-caller-file@1.0.2
├─ get-stream@3.0.0
├─ getpass@0.1.7
├─ glob-base@0.3.0
├─ glob-parent@2.0.0
├─ glob@7.1.2
├─ graceful-fs@4.1.11
├─ har-schema@1.0.5
├─ har-validator@4.2.1
├─ has-flag@2.0.0
├─ has-unicode@2.0.1
├─ hash-base@2.0.2
├─ hash.js@1.1.3
├─ hawk@3.1.3
├─ hmac-drbg@1.0.1
├─ hoek@2.16.3
├─ hosted-git-info@2.5.0
├─ http-signature@1.1.1
├─ https-browserify@0.0.1
├─ ieee754@1.1.8
├─ indexof@0.0.1
├─ inflight@1.0.6
├─ inherits@2.0.3
├─ ini@1.3.4
├─ interpret@1.0.4
├─ invert-kv@1.0.0
├─ is-arrayish@0.2.1
├─ is-binary-path@1.0.1
├─ is-buffer@1.1.6
├─ is-builtin-module@1.0.0
├─ is-dotfile@1.0.3
├─ is-equal-shallow@0.1.3
├─ is-extendable@0.1.1
├─ is-extglob@1.0.0
├─ is-fullwidth-code-point@1.0.0
├─ is-glob@2.0.1
├─ is-number@2.1.0
├─ is-posix-bracket@0.1.1
├─ is-primitive@2.0.0
├─ is-stream@1.1.0
├─ is-typedarray@1.0.0
├─ isarray@1.0.0
├─ isexe@2.0.0
├─ isobject@2.1.0
├─ isstream@0.1.2
├─ jsbn@0.1.1
├─ json-loader@0.5.7
├─ json-schema-traverse@0.3.1
├─ json-schema@0.2.3
├─ json-stable-stringify@1.0.1
├─ json-stringify-safe@5.0.1
├─ json5@0.5.1
├─ jsonify@0.0.0
├─ jsprim@1.4.1
├─ kind-of@3.2.2
├─ lazy-cache@1.0.4
├─ lcid@1.0.0
├─ load-json-file@2.0.0
├─ loader-runner@2.3.0
├─ loader-utils@1.1.0
├─ locate-path@2.0.0
├─ lodash@4.17.4
├─ longest@1.0.1
├─ lru-cache@4.1.1
├─ md5.js@1.3.4
├─ mem@1.1.0
├─ memory-fs@0.4.1
├─ micromatch@2.3.11
├─ miller-rabin@4.0.1
├─ mime-db@1.30.0
├─ mime-types@2.1.17
├─ mimic-fn@1.1.0
├─ minimalistic-assert@1.0.0
├─ minimalistic-crypto-utils@1.0.1
├─ minimatch@3.0.4
├─ minimist@0.0.8
├─ mkdirp@0.5.1
├─ ms@2.0.0
├─ nan@2.7.0
├─ node-libs-browser@2.0.0
├─ node-pre-gyp@0.6.39
├─ nopt@4.0.1
├─ normalize-package-data@2.4.0
├─ normalize-path@2.1.1
├─ npm-run-path@2.0.2
├─ npmlog@4.1.2
├─ number-is-nan@1.0.1
├─ oauth-sign@0.8.2
├─ object-assign@4.1.1
├─ object.omit@2.0.1
├─ once@1.4.0
├─ os-browserify@0.2.1
├─ os-homedir@1.0.2
├─ os-locale@2.1.0
├─ os-tmpdir@1.0.2
├─ osenv@0.1.4
├─ p-finally@1.0.0
├─ p-limit@1.1.0
├─ p-locate@2.0.0
├─ pako@0.2.9
├─ parse-asn1@5.1.0
├─ parse-glob@3.0.4
├─ parse-json@2.2.0
├─ path-browserify@0.0.0
├─ path-exists@3.0.0
├─ path-is-absolute@1.0.1
├─ path-key@2.0.1
├─ path-type@2.0.0
├─ pbkdf2@3.0.14
├─ performance-now@0.2.0
├─ pify@2.3.0
├─ preserve@0.2.0
├─ process-nextick-args@1.0.7
├─ process@0.11.10
├─ prr@0.0.0
├─ pseudomap@1.0.2
├─ public-encrypt@4.0.0
├─ punycode@1.4.1
├─ qs@6.4.0
├─ querystring-es3@0.2.1
├─ querystring@0.2.0
├─ randomatic@1.1.7
├─ randombytes@2.0.5
├─ randomfill@1.0.3
├─ rc@1.2.2
├─ read-pkg-up@2.0.0
├─ read-pkg@2.0.0
├─ readable-stream@2.3.3
├─ readdirp@2.1.0
├─ regex-cache@0.4.4
├─ remove-trailing-separator@1.1.0
├─ repeat-element@1.1.2
├─ repeat-string@1.6.1
├─ request@2.81.0
├─ require-directory@2.1.1
├─ require-main-filename@1.0.1
├─ right-align@0.1.3
├─ rimraf@2.6.2
├─ ripemd160@2.0.1
├─ safe-buffer@5.1.1
├─ semver@5.4.1
├─ set-blocking@2.0.0
├─ set-immediate-shim@1.0.1
├─ setimmediate@1.0.5
├─ sha.js@2.4.9
├─ shebang-command@1.2.0
├─ shebang-regex@1.0.0
├─ signal-exit@3.0.2
├─ sntp@1.0.9
├─ source-list-map@2.0.0
├─ source-map@0.5.7
├─ spdx-correct@1.0.2
├─ spdx-expression-parse@1.0.4
├─ spdx-license-ids@1.2.2
├─ sshpk@1.13.1
├─ stream-browserify@2.0.1
├─ stream-http@2.7.2
├─ string_decoder@0.10.31
├─ string-width@1.0.2
├─ stringstream@0.0.5
├─ strip-ansi@3.0.1
├─ strip-bom@3.0.0
├─ strip-eof@1.0.0
├─ strip-json-comments@2.0.1
├─ supports-color@4.5.0
├─ tapable@0.2.8
├─ tar-pack@3.4.1
├─ tar@2.2.1
├─ timers-browserify@2.0.4
├─ to-arraybuffer@1.0.1
├─ tough-cookie@2.3.3
├─ tty-browserify@0.0.0
├─ tunnel-agent@0.6.0
├─ tweetnacl@0.14.5
├─ uglify-js@2.8.29
├─ uglify-to-browserify@1.0.2
├─ uglifyjs-webpack-plugin@0.4.6
├─ uid-number@0.0.6
├─ url@0.11.0
├─ util-deprecate@1.0.2
├─ util@0.10.3
├─ uuid@3.1.0
├─ validate-npm-package-license@3.0.1
├─ verror@1.10.0
├─ vm-browserify@0.0.4
├─ watchpack@1.4.0
├─ webpack-sources@1.0.2
├─ webpack@3.8.1
├─ which-module@2.0.0
├─ which@1.3.0
├─ wide-align@1.1.2
├─ window-size@0.1.0
├─ wordwrap@0.0.2
├─ wrap-ansi@2.1.0
├─ wrappy@1.0.2
├─ xtend@4.0.1
├─ y18n@3.2.1
├─ yallist@2.1.2
├─ yargs-parser@7.0.0
└─ yargs@8.0.2
Done in 7.22s.

Holy moly is that a lot of stuff! I find it anxiety-inducing to watch the sheer volume of code being downloaded, and often wonder what problem that solves, but nevertheless, it should work. There will be ASCII art. There will be warnings that you have to ignore. But it should work, and you can verify it like so:

> $(yarn bin)/webpack --version
3.8.1

You've now taken your first step into a larger world, which is rife with version incompatibilities, masked or incorrect error messages, and inconsistent behavior, all so you can try to make your life easier while using one of the worst programming languages ever designed! Webpack is one of the least bad things you'll deal with.

With this out of the way, let's see Webpack actually do something.

A Very Simple Project

As we mentioned above, the purpose of Webpack is to take lots of JavaScript modules and produce a bundle that works in a browser, thus allowing you to write organized code.

In Webpack's parlance, the entry is the file it will read to find all other files. The output is the bundle that Webpack is creating and will be used in our browser.

Let's make a directory for our code called js:

> mkdir -p js

Now, we'll make our entry point in js/index.js like so:

console.log("Hello from index.js!");
import address from './address';
import billing from './billing';

address.announce();
billing.announce();

This is referencing two modules, address and billing. We'll create both of those in js/.

This is js/address.js:

console.log("Hello from address.js");
export default {
  announce: function() {
    console.log("Announcing address.js");
  }
}

And this is js/billing.js:

console.log("Hello from billing.js");
export default {
  announce: function() {
    console.log("Announcing billing.js");
  }
}

What we want is to produce a singe file called bundle.js that uses all this code.

We can do this without configuration per se, and just use CLI options:

> $(yarn bin)/webpack  --entry ./js/index.js  --output-filename=bundle.js
Hash: bd22d2dcd95071d10719
Version: webpack 3.8.1
Time: 91ms
    Asset    Size  Chunks             Chunk Names
bundle.js  3.5 kB       0  [emitted]  null
   [0] ./js/index.js 144 bytes {0} [built]
   [1] ./js/address.js 128 bytes {0} [built]
   [2] ./js/billing.js 128 bytes {0} [built]

Now, let's load this in a browser. Create index.html like so:

<!DOCTYPE html>
<html>
  <head>
    <script src="bundle.js"></script>
  </head>
  <h1>Open the Web Inspector</h1>
</html>

Open this in a browser, then open the JavaScript console. You should see all our messages:

Hello from address.js
Hello from billing.js
Hello from index.js!
Announcing address.js
Announcing billing.js

Ok then! That was neat!

We don't want to be building our JavaScript bundle from an ever-increasingly-complex command-line invocation. We also don't want the generated code being dumped in our root directory either, so let's set-up a tiny project structure to keep things organized.

Make webpack.config.js look like so:

const path = require('path');

module.exports = {
  entry: './js/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  }
};

This will do what we did before with Webpack, except it will place bundle.js inside dist/ instead of the current directory. This path must be absolute for reasons that are uninteresting and arbitrary. To satisfy this unnecessary requirement, we use the Node module path, which has a function resolve which will take our intention to use dist/ and specify the full path for Webpack.

Also, yes, this file is in the root directory of our project, which is unfortunate, but it'll make things easier for us for the time being, so just get used to it and be glad it's not called WebpackFile.

With this configuration in place, we can run it like so:

> $(yarn bin)/webpack
Hash: cfae12bd466ffc97c840
Version: webpack 3.8.1
Time: 99ms
    Asset    Size  Chunks             Chunk Names
bundle.js  3.5 kB       0  [emitted]  main
   [0] ./js/index.js 144 bytes {0} [built]
   [1] ./js/address.js 128 bytes {0} [built]
   [2] ./js/billing.js 128 bytes {0} [built]
> ls dist
bundle.js

Woot!

If we move our index.html into the newly-created dist:

> mv index.html dist

We can open that in a browser, open the JavaScript console, and see the same messages as before.

Hello from address.js
Hello from billing.js
Hello from index.js!
Announcing address.js
Announcing billing.js

The configuration file saves us some keystrokes, but even typing our $(yarn bin)/webpack etc etc is a bit cumbersome. We'll use a handy feature of package.json to create an alias for running webpack so we can just type yarn webpack.

We'll add a "scripts" key to package.json:

{
  "scripts": {
    "webpack": "webpack --config webpack.config.js --display-error-details"
  }
}

Yes, you can omit $(yarn bin) inside package.json like this—it knows to find webpack in the right place.

Your entire package.json looks like so:

> cat package.json
{
  "name": "work",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "webpack": "^3.8.1"
  },
  "scripts": {
    "webpack": "webpack --config webpack.config.js --display-error-details"
  }
}

And now:

> yarn webpack
yarn run v1.3.2
$ webpack --config webpack.config.js --display-error-details
Hash: cfae12bd466ffc97c840
Version: webpack 3.8.1
Time: 59ms
    Asset    Size  Chunks             Chunk Names
bundle.js  3.5 kB       0  [emitted]  main
   [0] ./js/index.js 144 bytes {0} [built]
   [1] ./js/address.js 128 bytes {0} [built]
   [2] ./js/billing.js 128 bytes {0} [built]
Done in 0.50s.

This is slightly better than a shell alias, because you can check it into source control.

Now What?

We're not even getting started—this was just an overview of what Webpack even is and why it exists. I found it personally helpful to go through this so I could see a very minimal use-case and learn the basic concepts, namely entry and output.

And just think how much we can accomplish with just eight lines of configuration. We can write JavaScript in a controlled way, putting code in files, and being organized.

So, what's next?

There's a lot we aren't doing, that we need to do on any real project, such as:

These are all possible with Webpack and also happen to be intended use-cases, however it's extremely hard to figure out how to do these things without someone just showing you the magical configuration needed to make them happen.

I don't like that. Boilerplate is just as tedious as “magic” and is just as intention-unrevealing. So, we're going to start with a problem to solve, and figure out together how to solve that with Webpack. There wil be digressions, yak shaving, and a few bumps in the road, but we'll get there.

The two next obvious things we might want to do are using third party libraries and unit testing. Since unit testing requires third party libraries, let's tackle third party libraries first by creating a more realistic application and bringing in some open source code to help write it.