How to extract multiple theme stylesheets with webpack?

后端 未结 2 1658
北恋
北恋 2021-02-02 00:51

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

From my current und

相关标签:
2条回答
  • 2021-02-02 00:54

    Here's your solution:

    npm i --save-dev file-loader
    

    In the loaders section, add this:

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

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

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

    The file loader writes files by filename, hash and extension so you are able to preserve the name.

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

    https://github.com/webpack/file-loader

    0 讨论(0)
  • 2021-02-02 01:00

    To avoid having to manually add the themes one possible solution is to create a function that reads contents of the themes folder and programatically add an entry for each *.scss file.

    Something along the lines of this:

    function getThemes(themePath) {
        var themes = {};
        fs.readdirSync(themePath).forEach(function(fileName) {
            var fileNameWithPath = path.join(themePath, fileName);
    
            var stat = fs.lstatSync(fileNameWithPath);
            if (stat.isDirectory()) return;
            if (!/\.scss$/.test(fileName)) return;
    
            var nameWithoutExt = path.basename(fileName, '.scss');
            themes[nameWithoutExt] = fileNameWithPath;
        });
    
        return themes;
    }
    
    var themes = getThemes('./src/scss/themes');
    
    var config= {
        entry: _.merge({ app: './src/js/init.js' }, themes),
        // rest of options
    };
    

    This will require you to restart your dev-server or re-run you webpack build when adding new theme files though, but at least you won't have to touch your webpack config.

    0 讨论(0)
提交回复
热议问题