Next.js客户端组件报错:Module not found: Can't resolve 'fs'
解决"Module not found: Can't resolve 'fs'"错误
问题根源
你在带有"use client"标识的客户端组件中,错误导入了后端框架express的json方法。express依赖Node.js内置的fs模块,但浏览器环境不支持该模块,因此webpack打包时会抛出找不到fs的错误。另外,fs是Node.js内置模块,无需通过npm i fs安装,安装也无法解决问题。
修复步骤
- 直接删除代码中不必要的导入语句:
import { json } from "express";
你的表单提交逻辑已经通过JSON.stringify处理请求体,完全不需要使用express的json方法。
修改后的完整代码
"use client"; import { useSession } from "next-auth/react"; import Image from "next/image"; import { redirect } from "next/navigation"; import { useState } from "react"; export default function ProfilePage() { const session = useSession(); const [userName, setUserName] = useState(session?.data?.user?.name || ""); const { status } = session; async function handleProfileInfoUpdate(ev) { ev.preventDefault(); const response = await fetch("/api/profile/", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: userName }), }); } if (status === "loading") { return "Loading...."; } if (status === "unauthenticated") { return redirect("/login"); } const userImage = session.data.user.image; return ( <section className="mt-8"> <h1 className="text-center text-primary mb-4">Profile</h1> <div className="max-w-md mx-auto "> <div className="flex gap-4 items-center"> <div> <div className=" px-2 rounded-lg relative"> <Image className="rounded-lg w-full h-full mb-1" src={userImage} width={259} height={250} alt="avatar" /> <button type="button">Edit</button> </div> </div> <form className="grow" onSubmit={handleProfileInfoUpdate}> <input type="text" placeholder="Input First and Last name" value={userName} onChange={(ev) => setUserName(ev.target.value)} /> <input type="email" disabled={true} value={session.data.user.email} /> <button type="submit">Save</button> </form> </div> </div> </section> ); }
补充说明
客户端组件运行在浏览器环境,只能使用浏览器支持的API和前端库,不要导入Node.js后端专属的模块(如express、fs等)。如果需要处理后端逻辑,应该放在Next.js的API路由文件中(app/api/或pages/api/目录下的文件),这些文件运行在Node.js环境,可以正常使用express和fs模块。
内容的提问来源于stack exchange,提问作者Gia Khánh Lê
相关产品推荐
相关产品推荐

