Intro to Webpack2

What is Webpack?

  • A manager for your front-end code 
  • Stuff that is nice for you to write => Stuff that is nice for your browser to read
  • Module bundler for Javascript
  • Compiler for Typescript/ES6/Sass/Less etc.
  • Enables code-splitting
  • Over a million downloads a week

How it works

  • Starts with the entry files
  • Follows the import/require chain
  • Bundles the final build

But actually how does it work?

Loaders

  • Customize your webpack
  • Loaders apply transformations or perform operations on files of a given type
    • ​HTML loader useful with Angular templates
    • Less loader converts Less to CSS
  • Built in + custom-made + NPM
  • Can be chained, applied to files via regex, excluded from files

Plugins

  • Plugins install custom functionality at any point in the webpack process
    • ​DLL plugin lets you create separate webpack bundles that reference each other
    • CommonsChunkPlugin creates a cache of vendor files

Hot Module Replacement

  • Allows updated application code to be injected into the application without requiring the browser to be refreshed
  • Updates when you save a file
  • For development stage only, requires webpack-dev-server
  • Uses WebSocket to alert the page of changes and updates DOM without refresh
  • "start": "webpack-dev-server --inline --hot"

What's new in Webpack2?

  • More ES6 support
    • understands import and export
  • Better performance, improved bundling
  • Performance budgets
    • highlights bundles that exceed 250kb
  • Treeshaking

Tree Shaking

  • Dead code elimination
  • Removes code that is not actually used/imported
  • Smaller bundles => happier web app
var path = require('path');

module.exports = {
  entry: './assets/js/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  // Add the JSHint loader
  module: {
    rules: [{
      test: /\.js$/, // Run the loader on all .js files
      exclude: /node_modules/, // ignore all files in the node_modules folder
      use: 'jshint-loader'
    },
    {
        test: /\.css$/,
        use: [ 'style-loader', 'css-loader?modules', ],
      }]
  },
  plugins: [
    // enable HMR globally
    new webpack.HotModuleReplacementPlugin(),

    //automatically turn vendor files into cached chunk
    new webpack.optimize.CommonsChunkPlugin({
        name: 'commons',
        filename: 'commons.js'
    })
  ],
   devtool: 'inline-source-map',
};

Meet the competition

  • Gulp
  • Bazel
  • Rollup
  • RequireJS
  • Browserify
  • Grunt

Further reading/viewing

  • Webpack: It's Not Magic | Naomi Jacobs | BuzzJS
    • https://www.youtube.com/watch?v=_QEM9kdV-b0
  • Beginner's Guide to Webpack 2
    • https://www.sitepoint.com/beginners-guide-to-webpack-2-and-module-bundling/
  • Bullet Three

deck

By borisonr

deck

  • 580