Exercise: Extracting CSS Part 1

In notebook:
FrontEndMasters Webpack Deep Dive
Created at:
2017-01-05
Updated:
2017-01-05
Tags:
JavaScript Webpack libraries React
We'll be using the ExtractTextPlugin for extracting the CSS. He will use the unreleased version of this plugin because it has a nicer API. 

Install the devDependency : ​ "extract-text-webpack-plugin": "2.0.0-beta.3",
We need the latest beta (v2). Most plugins are in beta, because Webpack itself is in beta. 

Then use it in Webpack config:
  // ****   webpack.config.babel.js   ****

/* eslint no-console:"off" */
..
const InlineManifestWebpackPlugin = require('inline-manifest-webpack-plugin')
// 1. ++++ include the plugin
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const webpackValidator = require('webpack-validator')
const {getIfUtils, removeEmpty} = require('webpack-config-utils')

module.exports = env => {
  const {ifProd, ifNotProd} = getIfUtils(env)
  const config = webpackValidator({
    context: resolve('src'),
    entry: {..},
    output: {..},
    devtool: ifProd('source-map', 'eval'),
    module: {
      // note: we're using loaders with ah 's'
      // and an array
      loaders: [
        {test: /\.js$/, loaders: ['babel'], exclude: /node_modules/},
        // 2.a ---- we can remove the styles loader
        // that was responsible for injecting the styles
        // remove this ↴
        // {test: /\.css$/, loaders: ['style', 'css']},
        
        // 2.b ++++ configure where to use it
        // add the loader for the styles
        {
          test: /\.css$/,
          loader: ExtractTextPlugin.extract({
            // not sure why you need the fallbackLoader
            fallbackLoader: 'style',
            // you would add SASS, stylus etc loaders here
            // (see the React workshop with Brian Holt)
            loader: 'css',
          })
        },
      ],
    },
    plugins: removeEmpty([
      new ProgressBarPlugin(),
      // 3. ++++ use it
      // conditional if prod or dev
      new ExtractTextPlugin(ifProd('styles.[name].[chunkhash].css', 'styles.[name].css')),
      ifProd(new InlineManifestWebpackPlugin()),
      ifProd(new webpack.optimize.CommonsChunkPlugin({
        names: ['vendor', 'manifest'],
      })),
      new HtmlWebpackPlugin({
        template: './index.html',
        // 4. ++++ we can remove the inject property
        // and the javascript will be at the bottom
        // and the styles at the top automatically
        // inject: 'head',
      }),
    ]),
  })
  if (env.debug) {..}
  return config
}

Now, at this point Webpack extracts the CSS to a separate CSS file. 
And Webpack even inserts the ​<link>​ tag for us in the html file because of the html plugin.