GatsbyJS重写html.js无效,无法添加Modernizr及WebFont库
解决Gatsby自定义标签不显示脚本的问题
嘿,我来帮你搞定这个Gatsby的标签问题!你遇到的情况其实挺常见的,咱们一步一步来解决:
1. 先清除Gatsby缓存(最可能的原因)
你修改了从.cache/default-html.js复制到src/html.js的文件,Gatsby的缓存机制有时候会“记住”旧的文件内容,导致你的修改没生效。解决步骤很简单:
- 先停止当前运行的
gatsby develop服务(按Ctrl+C) - 在终端运行命令:
gatsby clean - 重新启动开发服务:
gatsby develop
这时候刷新页面,检查标签,应该就能看到你添加的Modernizr和Google WebFont脚本了。
2. 确认html.js里的JSX写法是否正确
你提到是直接在html.js的JSX中添加<script></script>标签,要注意JSX的语法规范:
- 外部脚本的单标签需要闭合,比如:
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" />
(当然双标签写法<script src="..."></script>也可以,但没有内容的话用单标签更符合JSX规范)
- 检查脚本的
src或字体的href地址是否正确,有没有拼写错误,比如Google WebFont的链接是否能正常访问。
3. 其他添加内容的替代方法
如果清缓存和检查写法后还是不行,或者你想更灵活地管理内容,可以试试这些方法:
方法一:使用gatsby-plugin-head插件
这是Gatsby官方推荐的管理内容的插件,比直接修改html.js更灵活:
- 先安装插件:
npm install gatsby-plugin-head - 在
gatsby-config.js里启用插件:
module.exports = { plugins: [`gatsby-plugin-head`], }
- 在你的布局组件(比如
src/components/layout.js)里使用<Head>组件添加内容:
import { Head } from 'gatsby-plugin-head'; export default function Layout({ children }) { return ( <> <Head> <script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" /> <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet" /> </Head> <main>{children}</main> </> ); }
方法二:用专门的插件管理Google WebFonts
如果你只是想添加Google字体,可以用gatsby-plugin-google-fonts插件,它会自动帮你处理字体链接:
- 安装插件:
npm install gatsby-plugin-google-fonts - 在
gatsby-config.js里配置:
module.exports = { plugins: [ { resolve: `gatsby-plugin-google-fonts`, options: { fonts: [ `Roboto\:300,400,700`, // 指定字体和权重 `Open Sans` ], display: 'swap' // 优化字体加载体验 } } ] }
这样插件会自动把字体的<link>标签添加到里,不用你手动写。
内容的提问来源于stack exchange,提问作者Eric Johnson
相关产品推荐
相关产品推荐

