Search code examples
javascriptwebpackwalmart-electrode

How to have multiple css files with Electrode.io


I want to have my app use 2 separate css files (at the same time), generated from different files (1 from scss files, and one from less files); both file names should be hashed.

I currently have webpack configured to generate 2 css files; however, in dev mode, Electrode isn't consuming the second, and in prod mode, Electrode isn't consuming the first. The generated isomorphic loader file lists both (within the "main" chunk).

It appears the output into index.html gets generated in electrode-react-webapp/lib/default-handlers.js:65-68, which results in a single <link> tag. So I think I'm going about this wrong.

I'm on electrode-react-webapp: ^2.0.0 with webpack: ^3.0.0

const extractLess = new ExtractTextPlugin({
    allChunks: true,
    disable: isDev,
    filename: `semantic-ui${isDev ?  '' : '.[hash]'}.css`,
});

const extractSass = new ExtractTextPlugin({
    allChunks: true,
    disable: isDev,
    filename: `gemini${isBundling ? '[name]' : ''}${isDev ?  '' : '.[hash]'}.css`,
});

const lessRule = {
    test: /\.less$/,
    use: extractLess.extract({
        // …
    })
};

const sassRule = {
    test: /\.scss$/,
    use: extractSass.extract({
        // …
    })
};

// …

composer.addPartials([ // webpack-config-composer
    {
        'app-style': {
            config: {
                module: { rules: [ sassRule ] },
            },
        },
    },
    {
        'semantic-style': {
            config: {
                module: { rules: [ lessRule ] },
            },
        },
    },
]);

// register custom styles
const { _base } = composer.profiles;
const _extractStyle = _base.partials['_extract-style'];

_base.partials['app-style'] = { order: _extractStyle.order };
_base.partials['semantic-style'] = { order: _extractStyle.order };

delete _base.partials['_extract-style']; // `.enable = false` doesn't work

const config = compose();

Solution

  • This was not possible prior to Electrode React Webapp #715, released in v2.2.0.

    A couple small improvements to sample code provided in the PR:

    Don't add the second item in entry in webpack config (instead use import within your app)

    // /config/utils/chunk-selector.js
    module.exports = () => {
        const css = process.env.NODE_ENV === 'production'
            ? [
                'app',
                'third-party-something',
            ]
            : [];
    
        return: {
            css,
            js: 'app',
        };
    };
    

    This allows the second bundle to work with a style-loader fallback in dev mode.