我做了这样的事情。
我从 .cache 目录复制了默认的 html 并粘贴到 src 目录中。
我使用了以下命令:
cp .cache/default-html.js src/html.js
在 html.js 文件中,我注意到以下代码:
import React from "react"
import PropTypes from "prop-types"
export default function HTML(props) {
return (
<html {...props.htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
{props.headComponents}
</head>
<body {...props.bodyAttributes}>
{props.preBodyComponents}
<div
key={`body`}
id="___gatsby"
dangerouslySetInnerHTML={{ __html: props.body }}
/>
{props.postBodyComponents}
</body>
</html>
)
}
HTML.propTypes = {
htmlAttributes: PropTypes.object,
headComponents: PropTypes.array,
bodyAttributes: PropTypes.object,
preBodyComponents: PropTypes.array,
body: PropTypes.string,
postBodyComponents: PropTypes.array,
}
我放置了 SVG 加载器,它是一个图像和几行 CSS:
所以完整的代码是这样的:
import React from "react"
import PropTypes from "prop-types"
import LoaderSVG from './img/loader.svg'
export default function HTML(props) {
return (
<html {...props.htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
{props.headComponents}
</head>
<body {...props.bodyAttributes}>
{props.preBodyComponents}
<div
key={`loader`}
id="___loader"
style={{
alignItems: "center",
backgroundColor: "#F2F2F2",
display: "flex",
justifyContent: "center",
position: "absolute",
left: 0,
top: 0,
right: 0,
bottom: 0,
zIndex: 1,
}}
>
<img src={LoaderSVG} alt="" width="150"/>
</div>
<div
key={`body`}
id="___gatsby"
dangerouslySetInnerHTML={{ __html: props.body }}
/>
{props.postBodyComponents}
<script
dangerouslySetInnerHTML={{
__html: `
setTimeout(function() {
document.getElementById("___loader").style.display = "none"
}, 200)
`,
}}
/>
</body>
</html>
)
}
HTML.propTypes = {
htmlAttributes: PropTypes.object,
headComponents: PropTypes.array,
bodyAttributes: PropTypes.object,
preBodyComponents: PropTypes.array,
body: PropTypes.string,
postBodyComponents: PropTypes.array,
}
然后重启 Gatsby 就可以了。