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

NextJS中node_modules内try/require引发的'Can't resolve 'encoding''警告问询

NextJS 13.4.19 + Apollo Server 4.9.3:解决node-fetch缺失encoding的编译警告

问题根源

node-fetch里有一段可选依赖逻辑:尝试require('encoding')获取编码转换方法,失败就静默跳过。但NextJS的webpack构建会把这种可选依赖的缺失判定为警告抛出。而Apollo Server的schemaReporting插件依赖了node-fetch,因此触发了该警告。手动装encoding包能消警告,但这个依赖是可选功能(主要处理非UTF-8编码响应),大部分GraphQL场景用不上,属于冗余安装。

解决方案

方案1:让NextJS忽略特定警告

在项目根目录的next.config.js里添加webpack配置,精准过滤该警告:

/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config) => {
    config.ignoreWarnings = [
      {
        module: /node-fetch\/lib\/index\.js/,
        message: /Can't resolve 'encoding'/,
      },
    ];
    return config;
  },
};

module.exports = nextConfig;

这个配置只会忽略来自node-fetch/lib/index.js的“无法解析encoding”警告,不会影响其他正常警告的显示。

方案2:从根源切断警告触发路径

如果你的项目不需要Apollo Server的schema上报功能,可以直接禁用schemaReporting插件:

import { ApolloServer } from '@apollo/server';

const server = new ApolloServer({
  typeDefs,
  resolvers,
  // 禁用schema上报插件,避免加载依赖node-fetch的代码
  plugins: [],
  // 也可以更明确地关闭:
  // schemaReporting: false,
});

禁用后,Apollo Server不会加载用到node-fetch的schemaReporter模块,自然不会触发警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 08:12:34