解决全局安装包时的 EACCES 权限错误

如果你在尝试 全局安装一个软件包 时看到 EACCES 错误,你可以选择:

🌐 If you see an EACCES error when you try to install a package globally, you can either:

  • 使用 node 版本管理器重新安装 npm(推荐),

    or

  • 手动更改 npm 的默认目录

使用 node 版本管理器重新安装 npm

🌐 Reinstall npm with a node version manager

这是避免权限问题的最佳方式。要使用节点版本管理器重新安装 npm,请按照“下载和安装 Node.js 和 npm”中的步骤操作。在安装节点版本管理器之前,你无需删除当前的 npm 或 Node.js 版本。

🌐 This is the best way to avoid permissions issues. To reinstall npm with a node version manager, follow the steps in "Downloading and installing Node.js and npm". You do not need to remove your current version of npm or Node.js before installing a node version manager.

手动更改 npm 的默认目录

🌐 Manually change npm's default directory

注意: 本节不适用于 Microsoft Windows。

为了尽量减少权限错误的可能性,你可以配置 npm 使用不同的目录。在本例中,你将创建并使用位于主目录下的隐藏目录。

🌐 To minimize the chance of permissions errors, you can configure npm to use a different directory. In this example, you will create and use a hidden directory in your home directory.

  1. 配置 npm 以使用新的目录路径:

    npm config set prefix ~/.local
  2. 在你偏好的文本编辑器中,打开或创建一个 ~/.profile 文件,并添加这一行:

    PATH=~/.local/bin:$PATH

    如果你正在使用 zsh(可以通过运行 echo $0 来确认),你还需要将这一行添加到 ~/.zprofile 中:

    source ~/.profile
  3. 在命令行上,更新你的系统变量:

    source ~/.profile
  4. 要测试你的新配置,可以在不使用 sudo 的情况下全局安装一个软件包:

    npm install -g npm-check-updates

    运行它:

    ncu -g

npx:运行全局命令的替代方法

如果你使用的是 npm 5.2 或更高版本,你可能想考虑使用 npx 作为运行全局命令的替代方式,尤其是当你仅偶尔需要某个命令时。更多信息,请参见 关于 npx 的这篇文章

🌐 If you are using npm version 5.2 or greater, you may want to consider npx as an alternative way to run global commands, especially if you only need a command occasionally. For more information, see this article about npx.