JSPM

  • Created
  • Published
  • Downloads 29064
  • Score
    100M100P100Q145057F
  • License ISC

css hot reload work with extract-text-webpack-plugin

Package Exports

  • css-hot-loader

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (css-hot-loader) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

CSS Hot Loader

NPM version npm download

This is a css hot loader, which supprot hot module replacement for an extracted css file.

Why we need css hot loader

In most cases, we can realize css hot reload by style-loader . But style-loader need inject style tag into document, Before js ready, the web page will have no any style. That is not good experience.

Also, a lots of people thought about that, How can realize hot reload with extract-text-webpack-plugin. For example #30 , #!89.

So I write this loader, which supprot hot module replacement for an extracted css file.

Install

First install package from npm

$ npm install css-hot-loader --save-dev

Then config webpack.config.js

  module: {
    loaders: [{
      test: /\.less$/,
      loaders: [
        'css-hot-loader',
        'extract-text-webpack-plugin',
        'less',
        ...
       ],
      include: path.join(__dirname, 'src')
    }]
  }

css-hot-loader should be the first loader before extract-text-webpack-plugin.

webpack 2.x

Config file example should like this

module: {
  rules: [
    {
      test: /\.css$/,
      use: ['css-hot-loader'].concat(ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: 'css-loader'
      })),
    },
  ]
}

How

The realization principle of this loader is very simple. There are some assumed condition:

  1. css required by js , so css also be a js file
  2. The name of css file, which need hot reload , is the same as js file excuted.

The secend assumption is often established. If you use extract-text-webpack-plugin , entry foo.js will extract css file foo.css. This principle will help us to locate the url of css file extracted.

Because every css file will be a js module , every css file change can affect a module change. CSS hot loader will accept this kind change, then find extracted css file by document.currentScript.

So when a css file changed, We just need find which css file link element, and reload css file.

License

(The MIT License)