Search code examples
webpackwebpack-chain

Write MiniCssExtractPlugin in webpack-chain way


How to write the following in webpack-chain

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: '[name].css',
      chunkFilename: '[id].css',
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it uses publicPath in webpackOptions.output
              publicPath: '../',
              hmr: process.env.NODE_ENV === 'development',
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};

It will be great if there is a little explination I think that will help many people


Solution

  • config.plugin('css').use(MiniCssExtractPlugin, [{
           filename: '[name].css',
           chunkFilename: '[id].css',
    }])
    config.module.rule('css')
          .test(/\.css$/)
          .use('mini-css')
          .loader(MiniCssExtractPlugin.loader)
          .options({
               publicPath: '../',
               hmr: process.env.NODE_ENV === 'development',
           })
           .end()
           .use('css-loader')
           .loader('css-loader')