1

Is there any way to configure gatsby to inject a style file using a link tag?

currently, I have a global style (style.less) which I import it using a Layout Component. It's ok but It injects all CSS content into each page and bumps the page size.

I want to configure gatsby to load this style file using a link tag instead of injecting directly into DOM. webpack has an option for this purpose but I couldn't find anything similar for Gatsby.

Saman Mohamadi
  • 4,454
  • 4
  • 38
  • 58
  • 1
    This might be helpful: [How do I configure MiniCssExtractPlugin in Gatsby?](https://stackoverflow.com/questions/63124432/how-do-i-configure-mini-css-extract-plugin-in-gatsby) – coreyward Oct 12 '20 at 16:33

1 Answers1

0

Try:

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 allows you to customize the webpack's configuration by exposing some APIs (such as onCreateWebpackConfig or setWebpackConfig) functions.

The code is quite self-explanatory if you take into account the style-loader from webpack. Basically, you are setting some custom loaders for all files that match the regular expression, and finally, you override the default configuration with actions.replaceWebpackConfig(config).

For further details check Adding Custom webpack configuration docs.


In addition, regarding your original issue, you don't need to add your global styles in your Layout component since it will cause what you said, it will bump the page size. With Gatsby, you can use gatsby-browser.js API to add global styles like (in your gatsby-browser.js file):

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

Check the link you've provided (Standard Styling with Global CSS file).

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67