构建Next.js应用时遭遇follow-redirects的debug模块找不到警告
问题描述
构建应用时,第三方库follow-redirects抛出如下警告:
warn - ./node_modules/follow-redirects/debug.js
Module not found: Can't resolve 'debug' in 'G:\Workspace\node\MERN\client\node_modules\follow-redirects'
Did you mean './debug'?
Requests that should resolve in the current directory need to start with './'.
Requests that start with a name are treated as module requests and resolve within module directories (node_modules).
If changing the source code is not an option there is also a resolve options called 'preferRelative' which tries to resolve these kind of requests in the current directory too.
当前技术栈依赖:
"dependencies": { "@fortawesome/fontawesome-free": "^6.2.1", "axios": "^1.2.2", "bootstrap": "^5.2.3", "mdb-ui-kit": "^6.0.1", "next": "^13.1.1", "react": "^18.2.0", "react-dom": "^18.2.0", "react-toastify": "^9.1.1" }
follow-redirects的debug.js代码:
var debug; module.exports = function () { if (!debug) { try { /* eslint global-require: off */ debug = require("debug")("follow-redirects"); } catch (error) { /* */ } if (typeof debug !== "function") { debug = function () { /* */ }; } } debug.apply(null, arguments); };
index.js中的引入语句:
var url = require("url"); var URL = url.URL; var http = require("http"); var https = require("https"); var Writable = require("stream").Writable; var assert = require("assert"); var debug = require("./debug");
已尝试删除node_modules并重新安装依赖,问题未解决;查看该库仓库及issue,未发现相关报告,怀疑是自身配置导致。
可行解决方案
1. 安装debug依赖
follow-redirects将debug设为可选依赖(未在自身package.json中声明),但Next.js的模块解析逻辑会检测到未找到的依赖并抛出警告。直接安装debug即可消除警告:
npm install debug --save
2. 配置Next.js的preferRelative解析选项
若不想额外安装依赖,可在next.config.js中添加Webpack配置,开启preferRelative让解析器优先尝试当前目录(注:此方案主要针对路径误写场景,但可尝试解决当前警告):
/** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config) => { config.resolve.preferRelative = true; return config; }, }; module.exports = nextConfig;
3. 忽略特定警告
如果警告不影响应用功能,也可在next.config.js中配置忽略该条警告:
/** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config) => { config.ignoreWarnings = [ { module: /follow-redirects[\\/]debug\.js/, message: /Can't resolve 'debug'/, }, ]; return config; }, }; module.exports = nextConfig;
4. 锁定follow-redirects版本
有可能是当前安装的follow-redirects版本存在解析逻辑问题,可尝试锁定一个稳定版本,比如:
npm install follow-redirects@1.15.2 --save-exact
内容的提问来源于stack exchange,提问作者Dawid Adach

