Webpack

Peter Chen

2018/3/25

Why use Webpack?

  • Import multiple files
  • More than JavaScript
  • Task Runner

Import multiple files

function component() {
    var element = document.createElement('div');

    element.innerHTML = _.join(['Hello', 'webpack'], ' ');

    return element;
}

document.body.appendChild(component());
<!doctype html>
<html>
  <head>
    <title>Getting Started</title>
    <script src="https://unpkg.com/lodash@4.16.6"></script>
  </head>
  <body>
    <script src="./src/index.js"></script>
  </body>
</html>
  • Request
  • Order

More than JavaScript

Compile code to ES5 by Babel every time.

babel src -d dist

Task Runner

Uglify

need on Production

not need on Development

Webpack can resolve them

  • Import Multiple JavaScript
    • import file
    • set entry and output
    • <script>
  • More than JavaScript
    • set loader
  • Task Runner
    • set plugin
    • set env

Very Start Example

npm install webpack webpack-cli --save-dev

does not require a configuration file

npm run start
...
"scripts": {
  "start": "webpack"
},
...

Concepts

  • Entry
  • Output
  • Loaders
  • Plugins

Entry

An entry point indicates which module webpack should use to begin building out its internal dependency graph.

Default: ./src

module.exports = {
    entry: './source'
}

Output

The output property tells webpack where to emit the bundles it creates and how to name these files

const path = require('path');

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

Default: ./dist

Loaders

Loaders enable webpack to process more than just JavaScript files.

  • Babel
  • css
  • image
  • ...
npm install --save-dev babel-loader babel-core
// webpack.config.js
module.exports = {
    module: {
        rules: [
            { test: /\.js$/, use: 'babel-loader' }
        ]
    }
}

Plugins

bundle optimization and minification.

const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
    plugins: [
        new UglifyJsPlugin()
    ]
}

Loaders: before bundle

Plugins: after bundle

npm i -D uglifyjs-webpack-plugin

Thank You