Webpack 101

Nordnet Academy

Webpack

  • Module bundler
  • Takes modules with dependencies and generates static assets representing those modules

Webpack

Webpack

Webpack

  • Code splitting
    • sync and async loading of dependencies
  • Loaders
    • transforming resources, not only JS
  • Pre-/post processing
  • Live reload
  • Plugin system
    • rich plugin system for customization
    • Can I xyz? Yes, most probably.

Webpack

Basic setup

Webpack

  • Basic config
module.exports = {
  entry: './about',
  output: {
    filename: 'build.js'
  }
};

Webpack

  • External access to modules
module.exports = {
  entry: './about',
  output: {
    filename: 'build.js',
    library: 'app'
  }
};

Webpack

  • Watching for changes and source maps
module.exports = {
  entry: './about',
  output: {
    filename: 'build.js',
    library: 'app'
  },

  watchOptions: {
    aggregateTimeout: 100
  },

  devtool: 'inline-cheap-module-source-map'
};

Webpack

  • Environment variables
var webpack = require('webpack');
var NODE_ENV = process.env.NODE_ENV || 'development';

module.exports = {

  ...

  devtool: NODE_ENV === 'development' ? 'inline-cheap-module-source-map' : null,

  plugins: [
    new webpack.DefinePlugin({
      NODE_ENV: JSON.stringify(NODE_ENV)
    })
  ]
};

Webpack

  • Loaders
  • Resolving loaders
module.exports = {

  ...

  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel'
    }],
  },

  ...

};

Webpack

  • Plugins
module.exports = {

  ...

  plugins: [
    new webpack.DefinePlugin({
      NODE_ENV: JSON.stringify(NODE_ENV)
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        drop_console: true,
        unsafe: true,
      }
    }),
    new webpack.NoErrorsPlugin(),
  ]

  ...

};

Webpack

Code splitting

Webpack

  • Multiple entry points
module.exports = {
  context: __dirname + '/src',

  entry: {
    about: './about',
    profile: './profile'
  },

  output: {
    path: __dirname + '/public',
    publicPath: '/public/',
    filename: '[name].js',
    library: '[name]'
  },

  ...
};

Webpack

  • Common chunks
  • Profiling
module.exports = {

  ...

  plugins: [

      new webpack.optimize.CommonsChunkPlugin({
        name: 'common'
      }),

  ],

  ...

};

To be continued..

Made with Slides.com