Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a css file using webpack 4 and mini-css-extract-plugin?

I was able to get min-css-extract-plugin top generate css files just fine, but I can't seem to get it working with SASS. It runs great when I'm using the webpack dev server, but it keeps inserting my scss into my javascript file instead of creating a separate CSS file.

I have index.html, index.js and main.scss stored under /src

webpack.config.js:

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


module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          // fallback to style-loader in development
          process.env.NODE_ENV !== 'production' ? 'style-loader' : MiniCssExtractPlugin.loader,
          "css-loader",
          "sass-loader"
      ]
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  ]
}
like image 328
brunam Avatar asked Feb 06 '26 04:02

brunam


1 Answers

To have mini-css-extract-plugin actually extract your CSS into a separate file, you need to import your CSS (or other extension) into an entry file (index.js in your case). Additionally, using process.env.NODE_ENV's value to determine development or production settings inside your Webpack configuration does not actually work.

From Webpack's production configuration guide:

Contrary to expectations, process.env.NODE_ENV is not set to "production" within the build script webpack.config.js, see #2537. Thus, conditionals like process.env.NODE_ENV === 'production' ? '[name].[hash].bundle.js' : '[name].bundle.js' within webpack configurations do not work as expected.

You'll need to write your CSS rule without the style-loader for mini-css-extract-plugin's loader to take effect:

{
  test: /\.scss$/,
  use: [
    MiniCssExtractPlugin.loader,
    "css-loader",
    "sass-loader"
  ]
}

Then, since you remove style-loader from the rule, you need to create separate Webpack configurations for production and development so you can use it in development.

like image 91
Adam Avatar answered Feb 09 '26 16:02

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!