在 WSL 上安装包时出现 EACCESS 错误

EACCESS error when installing packages on WSL

我在尝试从 VS Code 在 WSL 上安装 NPM 包时遇到此错误。

npm ERR! Error: EACCES: permission denied, rename '/mnt/d/DEVRepo/PWS/functions/node_modules/cssstyle' -> '/mnt/d/DEVRepo/PWS/functions/node_modules/.cssstyle.DELETE'
npm ERR!  [OperationalError: EACCES: permission denied, rename '/mnt/d/DEVRepo/PWS/functions/node_modules/cssstyle' -> '/mnt/d/DEVRepo/PWS/functions/node_modules/.cssstyle.DELETE'] {     
npm ERR!   cause: [Error: EACCES: permission denied, rename '/mnt/d/DEVRepo/PWS/functions/node_modules/cssstyle' -> '/mnt/d/DEVRepo/PWS/functions/node_modules/.cssstyle.DELETE'] {        
npm ERR!     errno: -13,
npm ERR!     code: 'EACCES',
npm ERR!     syscall: 'rename',
npm ERR!     path: '/mnt/d/DEVRepo/PWS/functions/node_modules/cssstyle',
npm ERR!     dest: '/mnt/d/DEVRepo/PWS/functions/node_modules/.cssstyle.DELETE'
npm ERR!   },
npm ERR!   stack: "Error: EACCES: permission denied, rename '/mnt/d/DEVRepo/PWS/functions/node_modules/cssstyle' -> '/mnt/d/DEVRepo/PWS/functions/node_modules/.cssstyle.DELETE'",
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'rename',
npm ERR!   path: '/mnt/d/DEVRepo/PWS/functions/node_modules/cssstyle',
npm ERR!   dest: '/mnt/d/DEVRepo/PWS/functions/node_modules/.cssstyle.DELETE',
npm ERR!   parent: 'functions'
npm ERR! }

问题是 VSCode WSL 扩展锁定了文件并产生了错误。

解决方案是关闭 VSCode 上的 WSL 连接 o 再次关闭整个 IDE 和 运行 npm install 命令。

  • 在线下载“package-version.vsix”
  • 将“package-version.vsix”重命名为“package-version.zip”
  • 创建目录/home/user/.vscode-server/extensions/package-version
  • 将内容解压到“package-version.zip”
  • 将提取的 zip 存档的“扩展”文件夹的内容移动到 /home/user/.vscode-server/extensions/package-version
  • 连接wsl,现在会安装

您可以通过允许不安全的权限来修复该错误

npm config set unsafe-perm=true
npm install

https://github.com/microsoft/WSL/issues/14#issuecomment-207504657

终于找到了通过混合多个答案来升级 npm 的方法:

  • 运行 powershell 然后更改 wsl 分发版本
# List available distribution
PS C:\Users\CallMarl> wsl.exe -l
Debian (par défaut)
# set version to 2
PS C:\Users\CallMarl> wsl.exe --set-version Debian 2
  • 运行 wsl 然后安装最新版本
PS C:\Users\CallMarl> wsl.exe -d Debian
callmarl@LAPTOP ~ % sudo npm install -g npm@latest
  • 然后检查 npm 版本
callmarl@LAPTOP ~ % npm -v
7.20.3
  • 出于某种原因,您可以通过 运行 在 powershell wsl.exe --set-version Debian 1
  • 中回滚到 WSL 1

由于 wsl 不允许在没有 sudo 的情况下对 /usr/lib/node_modules 进行写操作,我们可以使用以下命令重新映射安装 node_modules 的位置。

mkdir ~/.npm-new
npm config set prefix '~/.npm-new'
export PATH=~/.npm-new/bin:$PATH
source ~/.profile

https://cmatskas.com/resolve-npm-access-denied-errors/