Introduction to
Webpack

Julien Tanguy, Sounderbox

Introduction to
Webpack

By Julien Tanguy

Another task runner ?

No

Another package manager ?

No

browserify on steroids

Packaging

  1. Entry point(s)
  2. Load dependencies transitively via loaders
  3. Apply plugins to the whole dependency tree

loaders

Converts files into commonJS modules

Other languages

import stylesheet from 'styles/my-styles.scss';
import logo from 'img/my-logo.svg';
import someTemplate from 'html/some-template.html';
console.log(stylesheet);
//"body{font-size:12px}"
console.log(logo);
//"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5[...]"
console.log(someTemplate);
//"<html><body><h1>Hello</h1></body></html>"

chainable

Lots of loaders

plugins

Uses

environment, commonsChunk, define, s3...

HMR & dev-server

code splitting

//static imports
import _ from 'lodash'

// dynamic imports
require.ensure([], function(require) {
  const d3 = require('d3')
  //do d3 stuff
  })

Configuration

module.exports = {
    entry: { /* Entry points */ },
    resolve: { /* File resolver */ },
    output: { /* Output config*/ },
    devServer: { /**/ },
    module: {
        loaders: [ /* loaders */ ],
        plugins: [ /* plugins */ ]
    }

Entry points and resolvers

entry: {
    bundle: "./src/index.js",
},
resolve: {
    extensions: ["", ".js", ".jsx", ".css", ".scss"]
},

Output and devServer

output: {
    path: path.join(__dirname, 'dist'),
    filename: "[name].js",
},
devServer: {
    outputPath: path.join(__dirname, 'dist')
},

Loaders

{
    test: /\.scss|\.css$/,
    loader: "style!css!sass"
},
{
    test: /\.js/,
    exclude: /(node_modules|bower_components)/,
    loader: "babel",
    query: {
        presets: ["es2015"]
    }
},
{
    test: /\.png|\.svg|\.jpg$/,
    loader: "url-loader",
    query: {
        limit: 100000 /*100 kb*/
    }
},

Plugins

new webpack.DefinePlugin({
    __DEVELOPMENT__: JSON.stringify(
        process.env.NODE_ENV === 'development' )
}),
new HtmlWebpackPlugin({
    title: 'My application',
    appMountId: 'app',
    inject: false,
    template: path.join(__dirname, 'assets', 'index.html')
})

Fork me on Github