3

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"
    })
  ]
}
2
  • What is in your index.js file? Commented Sep 18, 2018 at 22:59
  • Does the build create a CSS file in your output folder? If so, you might just need to use HtmlWebpackPlugin to load it in index.html. The css is working fine on the dev server because style-loader is injecting it as <style> tags at the top of the page. Commented Sep 25, 2018 at 1:03

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.