arie arie - 1 year ago 494
Sass (Sass) Question

How to extract multiple theme stylesheets with webpack?

I am trying to make a React app themable. For now themes only consist of different sets of sass variables which define different header colors, etc.

From my current understanding the

seems to be my best bet as I don't want my styles to be inlined and rather have separate files per theme.

So I created two themes:


The themes import the basic layout and common styles and override the relevant variables.

But the only way I managed to make webpack create separate css files
for both themes was to create distinct entry points for each theme in

entry: {
app: './src/js/init.js',
theme-a: './src/scss/themes/theme-a.scss',
theme-b: './src/scss/themes/theme-b.scss'

But adding a new entry point for every new theme that gets added feels wrong and I figure there must be a better way?

Answer Source

Here's your solution:

npm i file-loader

In the loaders section, add this:

    test: /themes\/.+\.scss$/,
    loader: "file-loader?name=./compiled-themes/css/[name].css!css!scss"

There may be more scss files, so there must be another section which bundles them as usual, but skips the themes

    test: /\.scss$/,
    exclude: /themes\/.+\.scss$/,
    loader: "css!scss"

The file loader writes files by filename, hash, extension so you get the change to preserve the name.

Note the name=./compiled-themes/css/[name].css part, where [] vars are substituted.