javascriptreactjswebpackwebpack-5mini-css-extract-plugin

webpack 5 and mini-css-extract-plugin doesn't load the css after saving the scss to css files


I have mini-css-extract-plugin that creates the css files from my scss files fine, but it when I load my pages (reactJs app), there are no styles loading. I suspect I am messing up the paths for output or import in some way, but I have tried many combinations unsuccessfully... The paths for import worked fine with the inline style-loader before. webpack entry:

entry: {    
        index: './src/index.js',
    },
    output: {
        filename: '[name].js'
    },

webpack module:

module: {
        rules: [
        {
        test: /\.(sass|less|css|scss)$/,
        sideEffects: true,
        use: [
          
           MiniCssExtractPlugin.loader,
          "css-loader",
          "sass-loader",
        ],
      },          
        {
          test: /\.js?$/,
          exclude: /node_modules/,              
          loader: 'babel-loader',          
          options:{
            presets: ['@babel/preset-react']
          }
        }

    ],          
  },

Webpack plugins:

plugins: [
        new MiniCssExtractPlugin({
          filename: "css/[name].css",
          chunkFilename: "css/[id].css",
        })
    ]

mainListing.js (which is one of the React routes inside of index.js):

import './css/index.scss'

Solution

  • With mini-css-extract-plugin you need to use html-webpack-plugin for automatic generation link tags or create index.html file with link tag.

    If you have any CSS assets in webpack's output (for example, CSS extracted with the MiniCssExtractPlugin) then these will be included with tags in the element of generated HTML. https://webpack.js.org/plugins/html-webpack-plugin/#basic-usage

    Webback team says: Note that if you import CSS from your webpack entrypoint or import styles in the initial chunk, mini-css-extract-plugin will not load this CSS into the page. Please use html-webpack-plugin for automatic generation link tags or create index.html file with link tag. https://webpack.js.org/plugins/mini-css-extract-plugin/