繁体   English   中英

带有 Next.js 的 og 图片元标记不起作用

[英]og image meta tag with Next.js is not working

<meta property="og:image" content="https://mywebsite.com/images/s1.jpg" 

我使用 next/head 并添加了上面的元标记图像,但是当我共享链接时图像没有出现。 我该如何解决?

对我来说它终于奏效了: Inside _app.js

import Head from "next/head"

然后在返回中:

<Head>
<meta property="og:image" content="https://myurl.com/ogImage.png" />
</Head>

然后我做了 static 导出并通过 FTP 从“out”文件夹上传文件,因为我在非节点服务器上托管该项目。 为此,打开“package.json”并将“export”更改为“next build && next export”。 然后只需运行 npm 在控制台中运行导出,文件将导出到 html

您可以在<head>标记中使用此元标记

<meta property="og:image" content="https://mywebsite.com/images/s1.jpg"/>

<meta property="og:title" content="Your Title"/>

<meta property="og:description" content="A full description of the page."/>

<meta property="og:image:width" content="1200"/>

<meta property="og:image:height" content="630"/>

请正确关闭您从标签中遗漏"/>"的元标签。

如下一篇文档中所说:

注意:Next.js 只会提供构建时位于公共目录中的资产。在运行时添加的文件将不可用。 我们建议使用 AWS S3 等第三方服务进行持久文件存储。

因此,Next 将<meta>标签视为动态内容,并且不进行任何构建时转换,这会导致不使用图像。

要解决此问题,您可以将图像上传到某个图像托管(甚至是您自己的网站),获取此链接并将其放入og:image ,或者您可以添加自定义 webpack 加载器来处理图像导入,如下所示:

import imageUrl from './logo.png';
import websiteUrl from './constants';

// somewhere in the head component
<meta property="og:image" content={`${websiteUrl}${imageUrl}`} />

在这里, websiteUrl指向您的生产网站的主机名,例如https://example.com

最后一个选项是添加<img src="/logo.jpg" alt="" style={{ display: 'none'}} /> 这确保 Next 将在构建时处理您的图像,并且您可以将<meta property="og:image" content={websiteUrl + '/logo.jpg'} />添加到头部。 好消息是浏览器最初不会加载显示设置为 none 的图像

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM