1

Folder structure:

src/index.tsx
src/themes/dark.scss
src/themes/light.scss
...

craco webpack modifications:

const path = require('path');

module.exports = {
  webpack: {
    configure: (webpackConfig, { env, paths }) => {
      webpackConfig.entry.push(
        path.join(process.cwd(), "src/themes/dark.scss"),
        path.join(process.cwd(), "src/themes/light.scss")
      );

      webpackConfig.module.rules.splice(1, 0, {
        test: /\.themes\/dark.scss$/,
        use: [
           { loader: require.resolve('sass-loader') },
           { loader: require.resolve('css-loader') }
        ]
      });

      webpackConfig.module.rules[3].oneOf[5].exclude = /\.(module|themes)\.(scss|sass)$/;
      webpackConfig.module.rules[3].oneOf[6].exclude = /\.themes\.(scss|sass)$/;
      webpackConfig.module.rules[3].oneOf[7].exclude.push(/\.themes\.(scss|sass)$/);

      return webpackConfig;
    }
  }
};

the intent is I am hoping obvious - we are trying to generate two theme css files from src/themes directory, which will be later changed manually with unloading / loading <link in DOM directly, I was inspired by Output 2 (or more) .css files with mini-css-extract-plugin in webpack and https://github.com/terence55/themes-switch/blob/master/src/index.js.

Now comes the troubles - after build process:

Creating an optimized production build...
Compiled successfully.

File sizes after gzip:

  122.24 KB  build/static/css/2.2e93dcba.chunk.css
  762 B      build/static/js/runtime~main.a8a9905a.js
  191 B      build/static/css/main.d0c4fa77.chunk.css
  157 B      build/static/js/main.2063d3e0.chunk.js
  109 B      build/static/js/2.9b95e8c0.chunk.js

(CSS files are OK, there are few generic CSS files and few of them are from libraries). But no theme files... I try to combine with file-loader, but it does not work either.

Jan Strnádek
  • 808
  • 5
  • 16

1 Answers1

1

I would recommend configuring webpack to pack all assets related to a particular theme into a single chunk:

const themeFileRegex = /(\w+)\.theme\.(scss|sass)$/;

// recursively searches for a theme stylesheet in parent issuers
function getIssuerTheme(module) {
  const matches = themeFileRegex.exec(module.resource);
  if (matches) {
    return matches[1];
  } else {
    return module.issuer && getIssuerTheme(module.issuer);
  }
}

...

webpackConfig.optimization.splitChunks.cacheGroups = {
    ...webpackConfig.optimization.splitChunks.cacheGroups,
    themes: {
       test: getIssuerTheme,
       name: m => {
         const name = getIssuerTheme(m);
         return `theme.${name}`;
       },
       reuseExistingChunk: false,
     },
   };

With that, you should get chunks named theme.light, theme.dark, etc.

gius
  • 9,289
  • 3
  • 33
  • 62