解决MAC在npm install XX 时报错:permission denied问题

在日常开发过程中,我们使用MAC执行 npm install -g 下载安装包的时候,经常会遇到如下报错:permission denied

报错详情

xxx@CN_C02xxxxx6M ~ % npm install -g yarn
npm ERR! code EACCES
npm ERR! syscall mkdir
npm ERR! path /usr/local/lib/node_modules/yarn
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/yarn'
npm ERR! [Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/yarn'] {
npm ERR! errno: -13,
npm ERR! code: 'EACCES',
npm ERR! syscall: 'mkdir',
npm ERR! path: '/usr/local/lib/node_modules/yarn'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.

npm ERR! A complete log of this run can be found in:
npm ERR! /Users/xxx/.npm/_logs/2022-12-06T11_15_27_852Z-debug-0.log

原理:

报这个错,根本原因是由于npm全局安装模块的默认路径没有权限,通常有以下几种方式解决:

  • 修改全局安装路径的权限(可能会不安全)
  • 修改默认安装路径(推荐)
  • 借助其他方式安装

解决方案

方案一:修改全局安装路径

step1:打开环境变量配置文件,配置环境变量

mkdir ~/.npm-global
npm config set prefix '~/.npm-global'

step2:

vim ~/.npm_global

吧下面内容粘贴到环境变量文件里:
export PATH=~/.npm-global/bin:$PATH

保存.bash_profile的文件,执行一下文件
source ~/.bash_profile
:w