Next.js API路由中无法解析'fs'模块的问题求助
解决Next.js API路由中
fs模块找不到的问题 问题原因
fs是Node.js专属的文件系统模块,浏览器环境中不存在。Next.js在打包时会检查所有代码模块,即使是仅在服务器端运行的API路由,也会被纳入客户端打包检查流程,从而触发Module not found: Can't resolve 'fs'错误。
解决方案
方案1:删除无用的fs引用
观察你的代码,const fs = require("fs");这行代码完全没有被使用,直接删除这行即可解决项目启动报错问题。修改后的代码:
export default function handler(req, res) { const id = req.query.id; if(id){ const schemas = require('../../pageSchemas/index.json'); res.end(JSON.stringify(schemas[id])); } }
方案2:配置Webpack忽略客户端的fs模块
如果确实需要在API路由中使用fs,在项目根目录的next.config.js中添加以下配置,告知Webpack在客户端打包时忽略fs模块:
module.exports = { webpack: (config, { isServer }) => { // 非服务器环境下,将fs模块设为false,避免打包报错 if (!isServer) { config.resolve.fallback = { ...config.resolve.fallback, fs: false }; } return config; } };
方案3:使用ES模块导入并确保服务器端执行
若采用ES模块语法导入fs,可直接在API路由中使用(API路由默认在服务器端运行),搭配上述Webpack配置即可正常工作:
import fs from 'fs/promises'; export default async function handler(req, res) { const id = req.query.id; if(id){ // 示例:用fs读取JSON文件 const schemaData = await fs.readFile('../../pageSchemas/index.json', 'utf8'); const schemas = JSON.parse(schemaData); res.end(JSON.stringify(schemas[id])); } }
内容的提问来源于stack exchange,提问作者noiseymur
相关产品推荐
相关产品推荐

