Search code examples
reactjswebpackwebpack-dev-serverwebpack-style-loaderreact-hot-loader

Webpack Extract CSS for Production, Inline for Development


I modified the React Hot Loader Boilerplate webpack.config.js so that it will export CSS into a separate file by adding the module:

{
    test: /\.scss$/,
    include: /src/,
    loader: ExtractTextPlugin.extract(
      'style',
      'css!postcss!sass'
    )
}

As well as the plugin:

new ExtractTextPlugin('app.css')

Here is the full webpack.config file for reference. While this correctly exports app.css when I run webpack, it kills the hot reload functionality for development. If I revert the module to:

{
    test: /\.scss$/,
    include: /src/,
    loaders: [
      'style',
      'css',
      'postcss-loader',
      'sass'
    ]
}

Hot reload works fine (adjusted webpack.config).

What is the best setup to easily switch between these two when I'm developing vs. exporting production ready code? In my mind, if I could use npm start (which just calls node server.js) to automatically use development mode, and then run webpack or webpack -p to automatically use production, that would be ideal.


Solution

  • Use process.env.NODE_ENV like what a typical React app usually use. like,

    "scripts": {
        "start": "NODE_ENV=development node server.js",
        ...
    

    and in the configuration file:

    var cssLoader;
    if (process.env.NODE_ENV === 'production') {
        cssLoader = { <... your production-use loader setup> }
    } else {
        cssLoader = { <... your development-use loader setup> }
    }
    ...
    loaders: [cssLoader, <...other loaders>]