【问题标题】:How to disable inline CSS in Gatsby?如何在 Gatsby 中禁用内联 CSS?
【发布时间】:2020-03-05 01:05:45
【问题描述】:

我用gatsby-starter-ghost创建了一个网站。

我注意到默认情况下,CSS 会作为内联样式放入每个 HTML 文件的头部:

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

我想在自己的文件中提供 CSS,而不是在每个 HTML 文件旁边。

如何禁用此行为并使用 &lt;link&gt; 代替 CSS?

【问题讨论】:

标签: css gatsby


【解决方案1】:

这似乎是不可配置的。我在Github 上找到了解决方案。基本上在您的gatsby-ssr.js 中重写style 元素,如下所示:

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']
        }
    })
}

【讨论】:

  • 在进行转换之前检查el.props['data-href'] 中是否有值是值得的,以避免影响自定义样式标签。您可以通过将第 7 行替换为 if (el.type === 'style' &amp;&amp; el.props['data-href'])
猜你喜欢
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 2019-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
相关资源
最近更新 更多