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

如果你在尝试 全局安装包 时看到 EACCES 错误,你可以:

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

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

    ¥Reinstall npm with a node version manager (recommended),

    or

  • 手动更改 npm 的默认目录

    ¥Manually change npm's default directory

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

¥Reinstall npm with a node version manager

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

¥Note: This section does not apply to 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 以使用新的目录路径:

    ¥Configure npm to use the new directory path:

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

    ¥In your preferred text editor, open or create a ~/.profile file and add this line:

    PATH=~/.local/bin:$PATH

    如果你使用的是 zsh(运行 echo $0 即可查看),则还需要将以下行添加到 ~/.zprofile

    ¥If you are using zsh (which you can find out by running echo $0), you will also need to add this line to ~/.zprofile:

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

    ¥On the command line, update your system variables:

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

    ¥To test your new configuration, install a package globally without using sudo:

    npm install -g npm-check-updates

    运行它:

    ¥And run it:

    ncu -g

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

¥npx: an alternative to running global commands

如果你使用的是 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.

npm v11.7 中文网 - 粤ICP备13048890号