Webpack 4: mini-css-extract-plugin + sass-loader + splitChunks

im doing someting like this in my Webpack 4 configuration.

const MiniCssExtractPlugin = require("mini-css-extract-plugin")

module: {
rules: [ {
    test: /\.scss$/,
    use: [
      MiniCssExtractPlugin.loader,
      {
        loader: "css-loader",
        options: {
          modules: true,
          sourceMap: true,
          importLoader: 2
        }
      },
      "sass-loader"
    ]}
  ]
},

plugins: [
  new MiniCssExtractPlugin({
    // Options similar to the same options in webpackOptions.output
    // both options are optional
    filename: "style.css",
    chunkFilename: "[name].css"
  })
]

I also give output.publicPath -configuration object to point into my build dir, example ->

output: {
   filename: "[name]-min.js",
   path: path.resolve(__dirname, "dist"),
   publicPath: "/static/react/dist/"
},

edit If you are interested in code splitting, Webpack 4 can do this “out of the box” for you. This will split .js and as well .css -files for you in case you use dynamic imports.

optimization: {
  splitChunks: {
    chunks: 'all'
  }
}

If you other hand would like to merge only your .css into one file you could add as follow.

optimization: {
    splitChunks: {
      chunks: 'all'
      cacheGroups: {
        styles: {
          name: 'styles',
          test: /\.s?css$/,
          chunks: 'all',
          minChunks: 1,
          reuseExistingChunk: true,
          enforce: true,
        },
      }
    },
}

Leave a Comment

tech