Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable inline CSS in Gatsby?

Tags:

css

gatsby

I created a website with gatsby-starter-ghost.

I noticed that by default the CSS is put into the head of every HTML file as an inline style:

<style>.every-thing-is-in-here {}</style>

I want to serve the CSS in its own file and not alongside every HTML file.

How can I disable this behaviour and use <link> for CSS instead?

like image 762
Marvin Rabe Avatar asked Jul 24 '19 17:07

Marvin Rabe


1 Answers

It seems this is not configurable. I found a solution on Github. Basically in your gatsby-ssr.js rewrite the style elements like this:

export const onPreRenderHTML = ({getHeadComponents}) => {
    if (process.env.NODE_ENV !== 'production')
        return

    getHeadComponents().forEach(el => {
        // Remove inline css.
        if (el.type === 'style') {
            el.type = 'link'
            el.props['href'] = el.props['data-href']
            el.props['rel'] = 'stylesheet'
            el.props['type'] = 'text/css'

            delete el.props['data-href']
            delete el.props['dangerouslySetInnerHTML']
        }
    })
}
like image 180
Marvin Rabe Avatar answered Sep 30 '22 20:09

Marvin Rabe