[英]Why is the typeof window check needed in Nextjs Image component
所以我制作了一个占位符图像/svg 来使用Nextjs 图像组件,我从他们的 repo 中复制了这段代码。 我对后端开发(主要是前端)不是很有经验,所以我不得不研究缓冲区、流、window.bto 等。我无法完全理解的是为什么需要typeof window === "undefined"
和 subsecuent代码行。 如果我删除它,它也有效。
我可以理解这是一个临界情况,就像“假设”一样。 但我无法理解为什么需要。 它总是会呈现给浏览器。 为什么要检查窗口是否未定义?
在此先感谢并抱歉英语不好,这不是我的主要语言。
Nextjs 代码
const shimmer = (w, h) => `
<svg width="${w}" height="${h}" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<linearGradient id="g">
<stop stop-color="#333" offset="20%" />
<stop stop-color="#222" offset="50%" />
<stop stop-color="#333" offset="70%" />
</linearGradient>
</defs>
<rect width="${w}" height="${h}" fill="#333" />
<rect id="r" width="${w}" height="${h}" fill="url(#g)" />
<animate xlink:href="#r" attributeName="x" from="-${w}" to="${w}" dur="1s" repeatCount="indefinite" />
</svg>`
const toBase64 = (str) =>
typeof window === 'undefined'
? Buffer.from(str).toString('base64')
: window.btoa(str)
const Shimmer = () => (
<div>
<ViewSource pathname="pages/shimmer.js" />
<h1>Image Component With Shimmer Data URL</h1>
<Image
alt="Mountains"
src="/mountains.jpg"
placeholder="blur"
blurDataURL={`data:image/svg+xml;base64,${toBase64(shimmer(700, 475))}`}
width={700}
height={475}
/>
</div>
我在组件上的实现
<Image
src={props.src}
layout={props.layout}
width={props.width}
height={props.height}
placeholder="blur"
blurDataURL={`data:image/svg+xml;base64,${toBase64(shimmer(300, 300))}`}
/>
Next.js 是 React 的框架,可帮助开发人员在 React 中管理服务器端渲染。
服务器端渲染有许多好处,包括:缓存特定页面(或仅缓存公共内容并保留用户特定数据或需要在前端加载的数据)。
由于 Next.js 正在执行服务器端渲染,这意味着有时他们会使用 Node.js 中的 react.toHTMLString() 函数。 他们将整个页面构建为 HTML 并将其发送给浏览网站的用户。 虽然它在 Node.js(服务器端渲染)中的服务器上运行,但在 Node.js 运行时中没有定义窗口,它可能会在渲染前崩溃。 在服务器上定义窗口也没有意义。
如果此代码作为预渲染(服务器端渲染或静态渲染)的一部分在服务器上运行,则不会有window
(因此对于 base64 编码没有window.btoa
),因为没有浏览器,而是可以利用 node.js 的Buffer
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.