【问题标题】:inject style into DOM using link tag in Gatsby在 Gatsby 中使用链接标签将样式注入 DOM
【发布时间】:2020-10-13 01:07:09
【问题描述】:

有没有办法配置 gatsby 使用链接标签注入样式文件?

目前,我有一个全局样式 (style.less),我使用 Layout Component 导入它。没关系,但它会将所有 CSS 内容注入每个页面并增大页面大小。

我想配置 gatsby 以使用链接标签加载此样式文件,而不是直接注入 DOM。 webpack 有一个 option 用于此目的,但我找不到与 Gatsby 类似的东西。

【问题讨论】:

标签: javascript reactjs webpack gatsby


【解决方案1】:

试试:

exports.onCreateWebpackConfig = ({ actions, loaders, getConfig }) => {
  const config = getConfig();

  config.module.rules = [
    ...config.module.rules.filter(rule => String(rule.test) !== String(/\.jsx?$/)),
    {
      test: /\.link\.css$/i,
      use: [
        { loader: `style-loader`, options: { injectType: `linkTag` } },
        { loader: `file-loader` },
      ],
    },
  ];
  actions.replaceWebpackConfig(config);
};

Gatsby 允许您通过公开一些 API(例如 onCreateWebpackConfigsetWebpackConfig)函数来自定义 webpack 的配置。

如果您考虑到style-loader from webpack,代码是不言自明的。基本上,您正在为所有匹配正则表达式的文件设置一些自定义加载器,最后,您使用actions.replaceWebpackConfig(config) 覆盖默认配置。

更多详情请查看Adding Custom webpack configuration docs


另外,关于你原来的问题,你不需要在你的Layout 组件中添加你的全局样式,因为它会导致你所说的,它会增加页面大小。使用 Gatsby,您可以使用 gatsby-browser.js API 添加全局样式,例如(在您的 gatsby-browser.js 文件中):

import './src/your/path/to/global/style.less';

检查您提供的链接 (Standard Styling with Global CSS file)。

【讨论】:

    猜你喜欢
    • 2020-02-07
    • 2012-01-10
    • 1970-01-01
    • 2012-03-14
    • 2021-10-12
    • 1970-01-01
    • 2021-09-29
    • 2019-09-05
    • 2012-05-18
    相关资源
    最近更新 更多