Webpack 5 Split chunks not working with scss imports

506 views Asked by At

I have a very basic webpack(v5.75.0) file setup:

webpack.config.js:

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

module.exports = {
  entry: {
    home: './src/home.js',
    about: './src/about.js'
  },

  mode: "development",
  
  resolve: {
      extensions: ['.js', '.jsx', '.scss']
  },

  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/[name].js',
    clean: true
  },

  module: {
    rules: [
      {
        test: /\.s[ac]ss$/i,
        use: [        
           MiniCssExtractPlugin.loader, "css-loader", "sass-loader",
        ],
      },
    ],
  },

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

  optimization: {
    splitChunks: {
      chunks: 'all',
      minSize: 0,      
    },
  }, 

};

Home.js:

import "./home.scss";

About.js:

@import "./about.scss";

home.scss:

@import "./card.scss";

about.scss

@import "./card.scss";

My understanding is that with my splitChunk settings, this should create a seperated stylesheet, with the card css, so I can share it around the project. However, all I get is an output of about.css and a home.scss, both containing the same card css, and no shared file is created.

interestingly, if I change both the imports in home/about.js to css instead:

@import "./card.css";

Then a separate chunk file is created, and the css is split perfectly.

Could anyone tell me what I have done wrong, please?

1

There are 1 answers

0
Benji40 On

Answering my own question. Turns out it was a very simple fix. I had to import all my page specific .scss into my home/about.js file, rather than trying to make a single entry scss file (that imports all the page specific scss).

I assume @import in scss is copying the css into the file(as it should), and doesn't care about chunking, like the js does.