該賞金到期in 4天。此問題的答案有資格獲得 200聲望獎勵。 emersonthis希望更多地關注這個問題。
我在 Next.js 應用程式上構建,當我安裝/匯入Plaiceholder(用于生成占位符影像)時,出現以下錯誤:Module not found: Can't resolve 'child_process'
- 節點 v14.18.0
- Next.js v11.1.2
- 占位符 v2.2.0
- 夏普 v0.29.2
我理解此錯誤訊息意味著 webpack5 正在嘗試捆綁客戶端不可用的節點包。但我不清楚它為什么這樣做。我沒有自定義任何 webpack 配置,并且在 Plaiceholder 檔案中找不到任何提及此問題的內容。我如何解決它?
注意:我希望在構建期間創建 base64 資料 URL,以便在頁面加載后立即可用(不在運行時異步獲取)。
這是我的 next.config.js
module.exports = {
reactStrictMode: true,
};
我的 package.json 只有scripts, dependencies, 和devDependencies(沒有改變模塊解析度)
如果相關,這里有一個使用 Plaiceholder 的簡化示例:
import Image from "next/image";
import { getPlaiceholder } from "plaiceholder";
import React, { useState } from "react";
...
const { base64 } = await getPlaiceholder(imgUrl);
...
return (<Image
src={imgUrl}
placeholder="blur"
blurDataURL={base64}
/>);
uj5u.com熱心網友回復:
似乎占位符不適合客戶端渲染。我相信該包適用于 Node.js 環境。這就是為什么當您嘗試在客戶端呈現組件時會收到此錯誤的原因。
要解決這個問題,您需要移至import { getPlaiceholder } from 'plaiceholder'NextJS API 部分。然后,您可以使用正文中的 URL 資料呼叫該 API。然后得到base64。
/api/getBase64.js
import { getPlaiceholder } from "plaiceholder";
export default async (req, res) => {
const { body } = req;
const { url } = body;
const { base64 } = getPlaiceholder(url);
res.status(200).send(base64);
};
/component.js
import Image from "next/image";
import React, { useState, useEffect } from "react";
const [base64, setBase64] = useState()
useEffect(() => {
(async () => {
const _base64 = await fetch.post('/api/getBase64', {url: imgUrl}); // wrote for demonstration
setBase64(_base64);
})()
})
return (<Image
src={imgUrl}
placeholder="blur"
blurDataURL={base64}
/>);
我知道blurDataURL在您獲取資料之前將是未定義的,但這是您可以使用plaiceholder庫來管理影像的方式。它應該僅為 NodeJS 環境匯入。如果你不喜歡這種方式,你可以嘗試尋找另一個同樣適用于瀏覽器環境(客戶端)的庫
根據評論更新:
如果你想base64在構建時生成這個,你可以getStaticProps在使用這個Image組件的頁面中使用。NextJS 足夠聰明,可以理解在客戶端或服務器端使用哪些庫。所以你可以這樣做:
import { getPlaiceholder } from "plaiceholder"; // place it at the root of file. This will not be bundled inside of client-side code
export async function getStaticProps(context) {
const { base64 } = await getPlaiceholder(imgUrl);
return {
props: { base64 }, // will be passed to the page component as props
}
}
This way, by using getStaticProps, the page will be created at build time. You can get the base64 prop inside of the page that uses the image component and pass that prop to blurDataURL. Also, you can use this approach with getServerSideProps too.
This is from NextJS website:
Note: You can import modules in top-level scope for use in getServerSideProps. Imports used in getServerSideProps will not be bundled for the client-side.
https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/359523.html
標籤:javascript 网络包 下一个.js 服务器端渲染
下一篇:電子表格中的IF函式引數有問題
