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

@grpc/grpc-js安装后缺失依赖,运行时报模块找不到错误求助

解决Next.js中@grpc/grpc-js找不到Node.js核心模块的问题

编译无错但运行时出现:

./node_modules/.pnpm/@grpc+grpc-js@1.8.12/node_modules/@grpc/grpc-js/build/src/channel-credentials.js:20:0
Module not found: Can't resolve 'tls'

同时tls、http2、net等Node.js核心模块均无法找到。

@grpc/grpc-js是为Node.js服务器环境开发的,依赖tls、net等Node.js专属核心模块,但Next.js客户端代码运行在浏览器环境中,浏览器不提供这些模块,因此出现找不到模块的错误。


方案1:将GRPC逻辑移至服务器端(推荐)

GRPC客户端通常用于服务端通信,把相关代码放在Next.js的API路由或服务器组件中,这些代码运行在Node.js环境下,天然支持所有核心模块。

示例:用API路由封装GRPC调用

  1. 创建pages/api/grpc-fetch.ts:
import type { NextApiRequest, NextApiResponse } from 'next';
import { ClientCredentials } from '@grpc/grpc-js';
// 导入你的proto生成的客户端类
import { YourServiceClient } from '../path/to/your/proto';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const client = new YourServiceClient(
    'your-grpc-server-address:port',
    ClientCredentials.createInsecure()
  );
  
  // 执行GRPC调用
  client.yourTargetMethod({ /* 请求参数 */ }, (err, response) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.status(200).json(response);
  });
}
  1. 在客户端页面pages/proto/index.tsx中通过fetch调用该API:
export default function GrpcPage() {
  const fetchGrpcData = async () => {
    const response = await fetch('/api/grpc-fetch');
    const data = await response.json();
    console.log(data);
  };

  return <button onClick={fetchGrpcData}>获取GRPC数据</button>;
}

方案2:配置Webpack fallback(仅用于客户端临时兼容,不推荐)

如果必须在客户端运行GRPC代码,可通过Next.js的Webpack配置,将缺失的Node模块置为空(多数核心模块无合适浏览器polyfill):

修改next.config.js:

/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config) => {
    // 配置fallback,跳过Node核心模块的解析
    config.resolve.fallback = {
      ...config.resolve.fallback,
      tls: false,
      net: false,
      dns: false,
      fs: false,
      http2: false,
    };
    return config;
  },
};

module.exports = nextConfig;

注意:此方法会导致GRPC-js的加密、TCP连接等核心功能失效,仅适用于无加密的本地测试场景。


方案3:检查依赖版本兼容性

确保@grpc/grpc-js和Next.js版本适配,建议更新至较新版本:

# 更新依赖
npm update @grpc/grpc-js next

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:12:54