升级Next.js从11.x.x到12后出现ReferenceError: process is not defined错误
问题描述
我在将项目从Next.js 11.x.x版本升级到最新的12版本后遇到了如下问题:
未处理运行时错误:
ReferenceError: process is not defined
以下是我的package.json配置:
{ "name": "tnhc-fe", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@hookform/resolvers": "^2.8.2", "axios": "^0.23.0", "jwt-decode": "^3.1.2", "local-storage": "^2.0.0", "moment": "^2.29.1", "next": "12", "next-i18next": "^8.9.0", "react": "^17.0.2", "react-dom": "^17.0.2", "react-hook-form": "^7.17.4", "yup": "^0.32.11", "zustand": "^3.5.13" }, "devDependencies": { "@types/jest": "^27.0.3", "@types/node": "^16.11.0", "@types/react": "17.0.30", "autoprefixer": "^10.3.7", "eslint": "8.0.1", "eslint-config-next": "11.1.2", "jest": "^27.4.3", "postcss": "^8.3.9", "tailwindcss": "^2.2.17", "typescript": "4.4.4" } }
解决方案
这个错误是Next.js 12默认启用Webpack 5作为构建工具导致的:Webpack 5移除了Node.js核心模块的自动注入逻辑,客户端侧代码默认无法访问全局process对象。你可以按照以下步骤修复:
- 修正环境变量暴露规则:所有需要在客户端代码(非服务端生命周期函数如getServerSideProps、getStaticProps)中访问的环境变量,必须在
.env系列配置文件中添加NEXT_PUBLIC_前缀。例如原process.env.API_URL需要修改为process.env.NEXT_PUBLIC_API_URL,修改完成后重启开发服务生效。 - 如果是第三方依赖内部调用了
process导致报错,你需要在next.config.js中手动配置全局注入规则:- 首先安装process浏览器兼容包:
npm install process --save- 调整
next.config.js配置如下:
/** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true, webpack: (config, { isServer }) => { if (!isServer) { // 配置process的浏览器fallback config.resolve.fallback = { ...config.resolve.fallback, process: require.resolve('process/browser'), } // 注入环境变量到客户端 config.plugins.push( new require('webpack').DefinePlugin({ 'process.env': JSON.stringify(process.env), }) ) } return config }, } module.exports = nextConfig - 升级匹配的ESLint配置:你当前
package.json中的eslint-config-next版本为11.1.2,与Next.js 12不兼容,升级后可避免不必要的编译校验问题:
npm install eslint-config-next@12 --save-dev
内容的提问来源于stack exchange,提问作者Rashed Rahat
相关产品推荐
相关产品推荐

