create-react-app创建React应用报npm ERR_SOCKET_TIMEOUT,常规排查后仍未解决
create-react-app初始化时npm Socket超时报错处理
触发场景
执行create-react-app完成项目目录生成、进入依赖安装环节时,拉取官方npm registry依赖触发报错,完整执行日志如下:
Creating a new React app in /home/abhijith/Desktop/React/firstReact/myapp. Installing packages. This might take a couple of minutes. Installing react, react-dom, and react-scripts with cra-template... npm ERR! code ERR_SOCKET_TIMEOUT npm ERR! errno ERR_SOCKET_TIMEOUT npm ERR! request to https://registry.npmjs.org/find-cache-dir failed, reason: Socket timeout npm ERR! A complete log of this run can be found in: npm ERR! /home/abhijith/.npm/_logs/2021-04-08T17_06_38_087Z-debug.log Aborting installation. npm install --save --save-exact --loglevel error react react-dom react-scripts cra-template has failed. Deleting generated file... package.json Deleting myapp/ from /home/abhijith/Desktop/React/firstReact Done.
已尝试的无效操作:
- 全局更新npm版本:执行
sudo npm update npm -g - 强制清理npm缓存:执行
npm cache clean --force - 完成上述操作后重新执行初始化命令,Socket超时报错仍稳定复现。
问题根因
报错本质是本地网络与npm官方源https://registry.npmjs.org的连通性不稳定,短时间连接中断就会触发ERR_SOCKET_TIMEOUT。更新npm版本、清理本地缓存的操作无法改善跨网连接的稳定性,因此无法解决该问题。
可落地解决步骤
- 切换npm全局拉取源为国内稳定镜像,执行命令:
npm config set registry https://registry.npmmirror.com
可通过npm config get registry命令验证配置是否生效 - 拉长npm默认请求的超时等待时间,降低短时间网络波动的影响,依次执行以下配置命令:
npm config set fetch-timeout 600000(设置单文件拉取最长等待10分钟)npm config set fetch-retry-mintimeout 20000(设置失败重试的最小等待间隔为20秒)npm config set fetch-retry-maxtimeout 120000(设置失败重试的最大等待间隔为2分钟)
- 配置完成后重新执行create-react-app初始化命令即可正常完成依赖安装
- 若不想修改全局npm配置,可在执行初始化命令时临时指定镜像源地址,直接使用以下命令创建项目:
npm init react-app myapp --registry=https://registry.npmmirror.com
内容的提问来源于stack exchange,提问作者abhijith v
相关产品推荐
相关产品推荐

