Webpack

The thing that could

What is it?

  • Toolset to build webapps
  • Module/Plugin oriented "compiler"
  • Asset management in a modular way
  • Require is supercharged
  • Plugins for development server (with livereload-like functionality)
  • So much more

Sample webpack.config.js

module.exports = {
  // Base directory for all the code, slightly optional but good practice
  context: 'src',
  // Entry file to start processing
  entry: [ './app/js/app.js' ],
  // Meat of how things are done
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loaders: ['babel-loader']
      },
      { test: /\.(gif|jpg|jpeg|png|webm)$/, loader: 'file-loader' }
    ]
  },
  // where it should be outputted to
  output: {
    filename: 'js/[name].js',
    path: path.join(__dirname, './dist'),
    publicPath: '/'
  },
  // where are the files found
  resolve: {
    modulesDirectories: ['node_modules']
  }
};

What are loaders

  • Instructions on how to load/process files
  • file-loader
    • require('../images/title.jpg')
    • Copies image to output directory
      • Might hash filenames
    • returns url that can be used in your app
  • url-loader
    • require('../fonts/comicsans.woff')
      • Inline/base64 content

Useful Loaders

  • Babel-loader
    • Adds the ability to write es6/es7 code and will add some shims to make it work in es5 browsers
  • html-loader
    • will process html page elements (img src by default) to find out what assets are needed
  • sass-loader/less-loader/postcss
    • Process css files
    • handle @import/url assets (example, fontawesome's font files)
  • markdown-loader/text-loader/json-loader
    • Process contents and returns usable strings
  • mustache-loader
    • Processes contents and returns template functions

Old/Normal

Webpack

module.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/messages', {
        templateUrl: 'partials/message-list.html',
        controller: 'MessageListCtrl'
      })
  }
])
module.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/messages', {
        template: require('./partials/message-list.html'),
        controller: 'MessageListCtrl'
      })
  }
])
  • Template is inlined (variable)
  • Always right template for version of code
  • can use require in template or controllers
    • html-loader makes it sexy
  • Template is "ajax"ed
  • Browser can cache old version

Preloaders?

  • I know a lot less about these
  • Examples
    • eslint-loader
      • Runs code through linter before build

Testing?

  • Sadly, have not played with this yet
  • karma-webpack looks pretty sweet 

Webpack

By Gavin Mogan