Search code examples
webpackpostcss

Use extractTextPlugin and postCss plugins in Webpack 2


I am migrating from webpack v1 to v2. I followed the official doc to update webpack.config.js:

...
module: {
    rules: [
        {
            test: /\.css$/,
            use: extractTextPlugin.extract({
                fallback: 'style-loader',
                use: [
                    'css-loader?modules&localIdentName=[path][name]_[local]--[hash:base64:8]',
                    'postcss-loader'
                ],
            }),
            exclude: [...]
        },
        {
            test: /\.css$/,
            use: extractTextPlugin.extract({
                fallback: 'style-loader',
                use: 'css-loader',
            }),
            include: [...]
        }
    ]
},
...
/**
 * postcss: [
 *   nested(),
 *   autoprefixer(),
 *   values
 * ]
 */

My problem is the postcss plugins(nested, autoprefixer, values). Webpack 2 didn't support custom property any more, and suggested use options.

I tried the options and plugins: () => [nested, autoprefixer, values] but can't make it work.

What's the proper way to do this? Thanks.


Solution

  • It is recommended to use a postcss.config.js file which exports an object with the options (see Postcss usage). Your config would look like this (omitting the import statements):

    module.exports = {
      plugins: [
        nested(),
        autoprefixer(),
        values
      ]
    }
    

    But if you want to, you can specify it directly in the webpack config (as shown in Postcss options):

    {
      test: /\.css$/,
      use: extractTextPlugin.extract({
        fallback: 'style-loader',
        use: [
          'css-loader?modules&localIdentName=[path][name]_[local]--[hash:base64:8]',
          {
            loader: 'postcss-loader',
            options: {
              plugins: () => [nested(), autoprefixer(), values]
            }
          }
        ]
      })
      exclude: [...]
    },
    

    Note that the options are on the loader itself, not the entire rule.