Instantly share code, notes, and snippets.

Embed
What would you like to do?
My sharing on HMR, generate slide with https://github.com/adamzap/landslide

Hot Module Replacing with Webpack


Me

Chen Yong, @jiyinyiyong


What is Webpack?

Webpack is a bundler for modules. The main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.

https://github.com/petehunt/webpack-howto


Features

  • Bundles both CommonJs and AMD modules.
  • Bundle splitting
  • Async loading
  • Packaging static assets like images and CSS
  • Loaders can preprocess files while compiling
  • Highly modular plugin system.

And...


Hot Module Replacement(HMR)

Hot Module Replacement (HMR) exchanges, adds, or removes modules while an application is running without a page reload.

http://webpack.github.io/docs/hot-module-replacement-with-webpack.html

  • react-hot-loader
  • babel-plugin-react-transform

How to HMR my code?

// check if HMR is enabled
if (module.hot) {
    // accept itself
    module.hot.accept();
    // removeStyleTag(element: HTMLStyleElement) => void
    var removeStyleTag = require("./removeStyleTag");
    // dispose handler
    module.hot.dispose(function() {
        // revoke the side effect
        removeStyleTag(element);
    });
}

https://github.com/webpack/docs/wiki/hot-module-replacement-with-webpack


Another example

// check if HMR is enabled
if (module.hot) {
    // accept update of dependency
    module.hot.accept("./handler.js", function() {
        // replace request handler of server
        server.removeListener("request", requestHandler);
        requestHandler = require("./handler.js");
        server.on("request", requestHandler);
    });
}

Usage

  • replace JSON configs
  • replace pure function
  • replace simple code with state(module.hot.dispose)

https://github.com/teambition/actions-recorder


So, is it really working on server side?

Yes!

  • Compile the server code with webpack
  • Use target: "node" or target: "async-node"
  • Enabled HMR via --hot or HotModuleReplacementPlugin
  • Use webpack/hot/poll or webpack/hot/signal
  • Run the bundle with node.

https://github.com/webpack/docs/issues/45 http://jlongster.com/Backend-Apps-with-Webpack--Part-I https://github.com/jiyinyiyong/webpack-backend-HMR-demo


Demo HMR server code

webpack = require 'webpack'
module.exports =
  entry: [ 'webpack/hot/poll?1000', './src']
  target: 'node'
  output:
    path: 'build/'
    filename: 'bundle.js'
  module:
    loaders: [
      {test: /\.coffee/, loader: 'coffee'}
    ]
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ]
  resolve:
    extensions: ['.js', '', '.coffee']

Usage

  • ...as frontend
  • replace code behind a WebSocket server!

Maybe a demo in the future


Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment