我已经找到了来源。使用 Next.js 时,包括在构建期间解析本地服务器资源的 NPM 包在内的所有模块都需要导入到仅限服务器端的模块中。这不像在通用网络应用程序中听起来那么简单。
在通用模块中执行类似以下人为的示例将导致如下错误:Can't resolve 'child_process' in 'C:\ua-demo\node_modules\nodemailer\lib\sendmail-transport' 因为child_process 是本机服务器资源.
// send-mail/server.js
import nodeMailer from 'nodemailer';
import config from './some/nodemailer/config;
const transport = nodeMailer.createTransport( config );
const sendMail = message => transport.sendMail( message );
export default sendMail;
// send-mail/browser.js
import { post } from 'axios';
const sendMail = async ( axiosRequestConfig ) => {
try {
await post( axiosRequestConfig );
} catch( e ) {
console.error( e );
}
};
export default sendMail;
// send-mail/index.js
import isBrowser from './some/browser/detection/logic';
import browserMailer from './browser';
import serverMailer from './server';
const mailer = isBrowser() ? browserMailer : serverMailer;
export default mailer;
将此“发送邮件”模块导入您的组件,并相信浏览器检查可确保在运行时适当的发送电子邮件逻辑。但是,构建失败并出现与上述类似的错误。此处的解决方案是修改 send-mail 模块以将其导入延迟到运行时。
// send-mail/index.js
import dynamic from 'next/dynamic'; // Can also use other lazy-loading module mechanism here. Since we are building a next.js app here, why not use the one created specifically for next apps?
import isBrowser from './some/browser/detection/logic';
const mailer = isBrowser()
? dynamic(() => import( './server' ))
: dynamic(() => import( './browser' ));
export default mailer;
如果使用 webpack,我们可以为客户端构建设置 RUN_TARGET=BROWSER 环境变量,并使用 webpack-conditional-loader 在构建时分支代码,而不是像这样动态运行时加载:
// #if process.env.RUN_TARGET !== 'BROWSER'
import serverMailer from './server';
// #endif
// #if process.env.RUN_TARGET === 'BROWSER'
import browserMailer from './browser';
// #endif
let mailer;
// #if process.env.RUN_TARGET !== 'BROWSER'
mailer = serverMailer;
// #endif
// #if process.env.RUN_TARGET === 'BROWSER'
mailer = browserMailer;
// #endif
export default mailer;
// yeilds the following after server-side build
import serverMailer from './server';
let mailer;
mailer = serverMailer;
export default mailer;
// yeilds the following after client-side build
import browserMailer from './browser';
let mailer;
mailer = browserMailer;
export default mailer;
您也可以选择删除 index.js 分支,并在仅服务器端模块中手动导入服务器电子邮件逻辑,在仅浏览器模块中导入浏览器电子邮件逻辑。在大型应用程序中,如果不是不可能处理,这可能会变得非常麻烦。不建议手动执行此操作。