6

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?

1

1 Answer 1

7

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']
        }
    })
}
1
  • It's worth checking that there is a value in el.props['data-href'] before doing the transformation, to avoid affecting custom style tags for example. You can do this by replacing line 7 with if (el.type === 'style' && el.props['data-href'])
    – adrian
    Jan 28, 2021 at 15:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.