How to generate separate css files for each page in react-static

387 Views Asked by At

I have an app that is built with react-static. I noticed that CSS for all pages (routes) are merged into one big styles.css file. Is it possible to generate separate CSS files for each page?

Now if I run build command there is one css file in the dist folder with css for both pages, I want to get separate css files for MainPage and AboutPage.

This is how my static.config.js file look like:

export default {
  getRoutes: async () => {
    return [
      {
        path: '/',
        template: 'src/pages/MainPage/MainPage.js',
      },
      {
        path: 'about',
        template: 'src/pages/AboutPage/AboutPage.js',
      },
    ]
  },
  plugins: [
    require.resolve('react-static-plugin-sass'),
    require.resolve('react-static-plugin-reach-router'),
    require.resolve('react-static-plugin-sitemap'),
  ],
}

And here is the full code: https://github.com/annmirosh/react-static-test

Appreciate your help!

1

There are 1 best solutions below

0
On

After some research, I figured out that it's described in the react-static Docs. There is an option extractCssChunks that can be added to the static.config.js:

export default {
  extractCssChunks: true,
  getRoutes: async () => {
    return [
      {
        path: '/',
        template: 'src/pages/MainPage/MainPage.js',
      },
      {
        path: 'about',
        template: 'src/pages/AboutPage/AboutPage.js',
      },
    ]
  },
  plugins: [
    require.resolve('react-static-plugin-sass'),
    require.resolve('react-static-plugin-reach-router'),
    require.resolve('react-static-plugin-sitemap'),
  ],
}

and it did exactly what I need - it enables automatic CSS splitting into separate files by routes