试试:
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(例如 onCreateWebpackConfig 或 setWebpackConfig)函数来自定义 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)。