You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Next.js的getServerSideProps中使用pg库时遇'fs模块未找到'错误求助

解决Next.js中pg库引入的"Can't resolve 'fs'"错误

核心问题是pg库依赖Node.js的fs模块,而页面顶部的import会被Next.js打包到客户端代码中,浏览器环境不存在fs导致报错。以下是几种可行的解决方法:

方法1:在getServerSideProps内动态导入pg

直接在服务端专属的getServerSideProps函数中动态导入pg,避免客户端代码加载该模块:

export async function getServerSideProps() {
  // 仅在服务端执行动态导入
  const { Client } = await import('pg');
  
  const client = new Client({
    // 填写你的数据库配置
    user: 'your_user',
    host: 'your_host',
    database: 'your_db',
    password: 'your_password',
    port: 5432,
  });

  await client.connect();
  const res = await client.query('SELECT * FROM your_table');
  await client.end();

  return {
    props: { data: res.rows },
  };
}

方法2:抽离数据库逻辑到服务端专属模块

把数据库连接、查询逻辑单独放到一个文件中,Next.js会自动识别这类仅在服务端运行的模块,不会打包到客户端:

  1. 创建lib/db.js文件:
import { Client } from 'pg';

export async function runQuery(sql, params = []) {
  const client = new Client({
    // 数据库配置
  });
  await client.connect();
  const result = await client.query(sql, params);
  await client.end();
  return result.rows;
}
  1. 在页面的getServerSideProps中导入并使用:
export async function getServerSideProps() {
  const { runQuery } = require('../lib/db');
  const data = await runQuery('SELECT * FROM your_table');
  
  return { props: { data } };
}

方法3:修改Webpack配置(不推荐,仅临时应急)

通过Next.js配置让Webpack在客户端打包时忽略fs模块:
在next.config.js中添加:

module.exports = {
  webpack: (config, { isServer }) => {
    if (!isServer) {
      config.resolve.fallback = {
        ...config.resolve.fallback,
        fs: false, // 客户端环境用空模块替代fs
      };
    }
    return config;
  },
};

注意:此方法只是掩盖错误,并非从根源解决,若后续pg库有依赖fs的逻辑意外跑到客户端,可能引发其他问题。

内容的提问来源于stack exchange,提问作者Stephen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 01:38:15