How to extract CSS to a `critical.css` stylesheet via an `import` statement with Webpack?

Viewed 552

Background

Our web application follows a component-based design pattern, with each component containing a template, Sass partial, and JavaScript module, like so:-

components/action_button/_action_button.html.erb
                        /_action_button.scss
                        /action_button.js

The JavaScript module imports the component's Sass partial and the template is rendered via Rails. Webpack is configured with a number of loaders and plugins to compile the styles and extract (via mini-css-extract-plugin) the resulting CSS into a standalone stylesheet for each entrypoint e.g.:-

home.js => home.js, home.css
search.js => search.js, search.css

Components are imported into entrypoints based on usage (i.e. if action_button is present on 'home', then it's rendered somewhere within the view and import '~/components/action_button/action_button.js'; is declared within home.js.

The Problem

In order to improve the page loading experience we're manually @importing a select few component Sass partials into a critical.scss entrypoint, the outputted CSS is then inlined into the <head> of the document and the full stylesheets are loaded asynchronously.

Ideally, we'd like to do this dynamically and one method I've thought of is denoting the criticality of a component via the import statement. Perhaps using a custom loader?:-

import 'critical-loader!~/components/action_button/action_button.js';

The issue is that I've little idea of how that Webpack loader would work. I essentially want it to leave all existing rules in-place, but redirect the extracted CSS from Sass partials imported from within it to critical.css.

Does anyone know of an existing solution or have any idea of where to begin with a problem like this?

0 Answers
Related