如何使用npm全局安装命令行工具,以便在不同的Node.js版本中保持可访问性?

huangapple go评论78阅读模式
英文:

How can I install a command-line tool globally using npm, so that it remains accessible across different Node.js versions?

问题

I am using nvm(Node Version Manager)来管理系统上的多个版本的 Node.js,并希望全局安装一个命令行工具,以便在使用 nvm use <version> 命令切换到不同的 Node.js 版本时仍然可以访问该工具。

我希望该工具能够全局可用,类似于 Python 的 pipx

我尝试使用 npm install -g <tool> 来全局安装命令行工具,但这种方法只会将工具安装在我当前使用 nvm 的特定版本的 Node.js 文件夹中。当我切换到不同的 Node.js 版本时,该工具将无法访问。

我希望全局安装的工具在 nvm 管理的所有 Node.js 版本中保持可访问,而不受我当前使用的版本的影响,我该如何实现这一点?

英文:

I am using nvm (Node Version Manager) to manage multiple versions of Node.js on my system and
i would like to install a command-line tool globally so that it remains accessible even when I switch to a different Node.js version using the nvm use <version> command.

I want the tool to be available globally, similar to how pipx with Python.

I have tried installing the command-line tool globally using npm install -g <tool>. However, this approach only installs the tool within the Node.js folder of the specific version I am currently using with nvm. When I switch to a different Node.js version, the tool becomes inaccessible.

I Want the globally installed tool to remain accessible across all Node.js versions managed by nvm, regardless of the version I am currently using, so how can I achieve this?

答案1

得分: 2

没有办法使用 NVM 来做到这一点,因为 NVM 为每个 Node 版本维护了一个隔离的环境。

您可以创建一个安装包的脚本,该脚本会在您已安装的所有版本上安装该包:

#!/bin/bash

PACKAGE="your-package"

versions=$(nvm ls --no-colors | grep -o -E 'v[0-9]+\.[0-9]+\.[0-9]+')

for version in $versions
do
  echo "Installing $PACKAGE on Node.js $version..."
  nvm install $version
  npm install -g $PACKAGE
done
英文:

There's no way to do that with NVM because NVM keeps an isolated environment for each Node version.

You can make a script that installs a package on all versions that you have installed:

#!/bin/bash

PACKAGE="your-package"

versions=$(nvm ls --no-colors | grep -o -E 'v[0-9]+\.[0-9]+\.[0-9]+')

for version in $versions
do
  echo "Installing $PACKAGE on Node.js $version..."
  nvm install $version
  npm install -g $PACKAGE
done

huangapple
  • 本文由 发表于 2023年6月30日 00:57:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76583147.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定