如何为Gatsby站点的<html>标签添加AMP必填属性以识别为AMP网站
Hey there! Let's tackle your question about adding required AMP attributes to the <html> tag—first for Gatsby, then for general HTML setups.
In Gatsby: Add AMP Attributes to the <html> Tag
Gatsby lets you modify the root HTML structure via its server-side rendering (SSR) API. Here's how to do it:
- First, create or edit the
gatsby-ssr.jsfile in your project's root directory (this file controls how Gatsby renders HTML on the server). - Export the
onRenderBodyfunction, which gives you access to thesetHtmlAttributesmethod. Use this to add the requiredampattribute (and any other attributes likelangyou need).
Here's a working code example:
exports.onRenderBody = ({ setHtmlAttributes }) => { setHtmlAttributes({ amp: true, lang: "en" // Optional but recommended for accessibility }); };
When you build or run your Gatsby site, this will generate an <html> tag like <html amp lang="en">—which meets AMP's mandatory requirement.
If you're using the official gatsby-plugin-amp, double-check its configuration, but manually setting attributes via onRenderBody gives you direct control over the final output.
General HTML Scenario: Add AMP Attributes
For static HTML sites or non-Gatsby frameworks, it's straightforward—just edit your root HTML file directly:
- Add the
ampattribute (or the equivalent⚡lightning symbol) directly to the<html>tag:
<html amp lang="en"> <!-- OR --> <html ⚡ lang="en">
- Remember, AMP requires more than just this attribute. You'll also need to include the AMP core script in your
<head>section:
<script async src="https://cdn.ampproject.org/v0.js"></script>
And make sure all other elements on the page follow AMP's rules (like using <amp-img> instead of standard <img> tags, avoiding custom JavaScript, etc.).
内容的提问来源于stack exchange,提问作者nyedidikeke

