React项目出现process未定义错误,多种解决方案无效求助
解决Create React App中引入guardian-wallet导致的process未定义错误
问题说明
基于Create React App构建的项目引入guardian-wallet依赖后,触发错误:Uncaught ReferenceError: process is not defined at ./node_modules/process-nextick-args/index.js。已尝试升级react-scripts至最新版本、安装指定版本react-error-overlay@6.0.9、添加resolutions配置、清理node_modules与缓存后重装依赖等操作,均未解决问题。
项目相关代码如下:
package.json
{ "name": "new-app", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^14.4.3", "buffer": "^6.0.3", "dotenv": "^16.0.3", "guardian-wallet": "^0.0.6-rc.30", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "^5.0.1", "web-vitals": "^3.1.1" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "preinstall": "npx npm-force-resolutions" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "react-error-overlay": "^6.0.11" }, "resolutions": { "//": "See https://github.com/facebook/create-react-app/issues/11773", "react-error-overlay": "6.0.9" } }
App.js
import logo from './logo.svg'; import './App.css'; import GuardianWallet from "guardian-wallet";
可行解决方案
方案1:手动注入process全局变量
Create React App v5及以上版本不再自动向浏览器注入Node.js环境变量,而guardian-wallet依赖的process-nextick-args包需要用到process对象。可以通过以下步骤手动注入:
- 安装
process包:
npm install process --save
- 在
public/index.html中添加脚本,在React加载前定义全局process:
<script> window.process = { env: { NODE_ENV: '%NODE_ENV%' } }; </script>
方案2:用react-app-rewired修改webpack配置
无需eject项目,通过react-app-rewired自定义webpack配置来提供process变量:
- 安装依赖:
npm install react-app-rewired process --save-dev
- 在项目根目录创建
config-overrides.js文件,写入配置:
const webpack = require('webpack'); module.exports = function override(config) { config.plugins.push( new webpack.ProvidePlugin({ process: 'process/browser', }) ); return config; };
- 修改
package.json中的scripts命令:
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-scripts eject", "preinstall": "npx npm-force-resolutions" }
方案3:降级react-scripts到v4版本
v4版本的react-scripts默认会向浏览器注入process变量,可尝试降级:
- 卸载当前版本:
npm uninstall react-scripts
- 安装v4.x版本:
npm install react-scripts@4.0.3 --save
- 清理依赖并重装:
rm -rf node_modules package-lock.json npm install
内容的提问来源于stack exchange,提问作者gauthami vijay
相关产品推荐
相关产品推荐

