Search code examples
reactjswebpackdevopsvitebundler

React with Vite v5 does not code split SCSS files into multiple CSS chunks in production build


I want to enable CSS code splitting with my .scss files using Vite, but for some reason it only works in dev and when I do a production build, I only get one index.css file.

I have no idea why this is happening. I looked everywhere, and it seems no one has this issue. I tried a random TS + Vite + React project and css code splitting does not work there as well.

Here is my config file:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'

/**
 * Vite plugins, react must always be present!
 */
let plugins = [react({})]

export default defineConfig(() => {
  return {
    root: '.',
    publicDir: `${reactSrc}/public`,
    jsx: 'react',
    plugins: [react()],

    server: {
      port: envConfig?.port,
      host: envConfig?.host || '0.0.0.0',
    },

    // Preview server options, runs only when there is a bundle to serve
    preview: {
      port: envConfig?.port,
      host: envConfig?.host || '0.0.0.0',
    },

    // Build options when the app is built in production mode
    build: {
      cssCodeSplit: true,
    },
  }
})

Here is how I use a SCSS module

import styleClass from '../../scss/components/Button.module.scss'

  if (buttonType.login === type) {
    return (
      <button
        className={`${styleClass[`${block}--${type}`]} ${className}`}
        onClick={onClick}
//...............

I even tried with normal vanilla .css files, can't get it to work, always ends up in one file when production build finishes

Output

My main.scss file is imported in main.tsx component.

Tried a lot of build options, my expectations are to have multiple .css files in production mode


Solution

  • The solution was to simply lazy load the component where the scss module is imported.