Webpack

Overview

Webpack can often replace Grunt or Gulp because it can transpile Javascript and CSS, and intelligently concatenate files together. It supports various module systems such as AMD, CommonJS, ES6, and Angular.

Some resources for learning Webpack:

Config File

There are some important top-level objects in the config file that you should understand.

Entry and Output (required elements)

These are the only required keys in the config file. Entry specifies a javascript file that is your top-level module. In other words, there are no other modules that include (import) it. The entry file is, by convention, often named index.js or main.js.

Output holds informtion about how to construct the bundled file. Remember, the primary purpose of Webpack is to take multiple files (the entry point and all its dependencies) and concatenate all of them into one Javascript file that can be put on a webpack via a <script> tag.

Output Cheatsheet

This is a summary of how Webpack will create the bundle depending on your libraryTarget and externals definition.

The following table assumes you have configured your externals as:

externals: {
    jquery: {
        var: '$',
        commonjs: 'jquery',
        commonjs2: 'jquery',
        amd: 'jquery'
    }
}

Line two is how you reference the library in your code. e.g.

import $ from 'jquery';
libraryTarget How you should make externals available.
How Webpack requests the module.
library
var <script> tag
module.exports = jQuery

Take aways: When specifying the library name key, all it does is assigns your bundle to that name. This is not-applicable when the `libraryTarget` is `commonjs2` because that module system doesn’t use names.

Module Resolution

Webpack can natively consume CommonJS, CommonJS2, and ES6 (Harmony) modules directly. It can even mix-and-match modules systems. That is, you can import a CommonJS module and require() an ES6 module. That is certainly not recommended because it is just plain confusing to do so.

Optimization and Analysis

The bottom of the Code Splitting page has a list of code analyzer tools.

Use these tools to ensure the final bundle is constructed as you expect. Problems? Take a look at your stats file, it might have comments in it that make it an invalid JSON file.