How to extract critical (above the fold) CSS from each entry?
Asked Answered
S

1

11

I have a simple multi-page app with three pages, my webpack.config.js entry looks like:

{
  entry: {
    a: 'pages/a.js',
    b: 'pages/b.js',
    c: 'pages/c.js',
  }
}

Each page consists of several React components, some of which are visible above-the-fold on first render, and some of which are out of view.

I'd like to declaratively define which components are 'critical' (above-the-fold) for each page/entry, and have that CSS extracted into a separate file. Something like:

{
  a: ['compononents/button/style.css', ...],
  b: ['compononents/title/style.css', ...],
  c: ['compononents/header/style.css', ...]
}

outputting something like:

- dist/a.critical.css
- dist/b.critical.css
- dist/c.critical.css

I've been playing around with the extract-text-webpack-plugin, but can't seem to find a way to tell it to only extract specific CSS in the context of a specific entry.


How can I extract specific CSS file content when in the context of a specific entry/page?

Samekh answered 24/10, 2017 at 15:11 Comment(1)
Have you see html-critical-webpack-plugin and webpack-critical?Waterrepellent
S
1

I'm in the same situation, our project is big enough and we need more than 20 different critical css files. I found a way to make generating critical CSS more painless. I'm using https://github.com/zgreen/postcss-critical-css which allow creating different critical css files.

@critical crit.css {
    .head {
        background: red;
    }

    .head .logo {
        display: block
    }
}

@critical v2.css {
    .head.v2 {
        background: green;
    }
}

.main {
    color: #333;
}

.footer {
   background: black;
}

Postcss-critical-css will generate 3 files - my css file (with or without critical styles) and 2 critical css files - v2.css and crit.css

Hope this will help you!

Selfstyled answered 7/12, 2017 at 21:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.