Contents

Webpack Overview

webpack is a static module bundler for modern JavaScript applications.

Document: https://webpack.js.org/concepts/

Installation

1
npm i -D webpack webpack-cli

webpack core concept

Entry

An entry point indicates which module webpack should use to begin building out its internal dependency graph. webpack will figure out which other modules and libraries that entry point depends on (directly and indirectly).

Output

The output property tells webpack where to emit the bundles it creates and how to name these files. It defaults to ./dist/main.js for the main output file and to the ./dist folder for any other generated file.

Loaders

Out of the box, webpack only understands JavaScript and JSON files. Loaders allow webpack to process other types of files and convert them into valid modules that can be consumed by your application and added to the dependency graph.

Plugin

While loaders are used to transform certain types of modules, plugins can be leveraged to perform a wider range of tasks like bundle optimization, asset management and injection of environment variables.

Mode

By setting the mode parameter to either development, production or none, you can enable webpack’s built-in optimizations that correspond to each environment

Example

In webpack.config.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const debug = process.env.NODE_ENV !== 'production';
const webpack = require('webpack');
const path = require('path');

module.exports = {
    mode: 'development',
    context: path.join(__dirname, 'src'),
    devtool: debug ? 'inline-sourcemap' : false,
    entry: './js/client.js',
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015', 'stage-0'],
                    plugins: [
                        'react-html-attrs',
                        'transform-decorators-legacy',
                        'transform-class-properties',
                    ],
                },
            },
        ],
    },
    output: {
        path: __dirname + '/src/',
        filename: 'client.min.js',
    },
    plugins: debug
        ? []
        : [
              new webpack.optimize.DedupePlugin(),
              new webpack.optimize.OccurrenceOrderPlugin(),
              new webpack.optimize.UglifyJsPlugin({
                  mangle: false,
                  sourcemap: false,
              }),
          ],
};