解决全局安装包时的 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 hidden directory in your home directory.

  1. 备份你的计算机。

    ¥Back up your computer.

  2. 在命令行的主目录中,为全局安装创建一个目录:

    ¥On the command line, in your home directory, create a directory for global installations:

    mkdir ~/.npm-global
  3. 配置 npm 以使用新的目录路径:

    ¥Configure npm to use the new directory path:

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

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

    export PATH=~/.npm-global/bin:$PATH
  5. 在命令行上,更新你的系统变量:

    ¥On the command line, update your system variables:

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

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

    npm install -g jshint

除了步骤 3-5,你可以使用相应的 ENV 变量(例如,如果你不想修改 ~/.profile):

¥Instead of steps 3-5, you can use the corresponding ENV variable (e.g. if you don't want to modify ~/.profile):

NPM_CONFIG_PREFIX=~/.npm-global

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 中文网 - 粤ICP备13048890号