How to change npm version

How to change npm version

How to update npm package to latest version? [Complete Guide]

If you are looking to update npm package and don’t know how to do that, Then this blog post «How to Update npm package to the latest version» will guide you on how to do that.

List of content you will read in this article:

After the introduction of JavaScript, developers got the advantage of creating websites and web-based applications efficiently. It offers numerous resources and libraries to make the development job much more comfortable. In the beginning, it was easier and efficient to maintain this wide range of libraries, but with time we needed a mature solution to handle them. This article will give you a brief about how to update NPM package?

It is when NPM (Node Package Manager) was introduced as a JavaScript package manager commonly used in conjunction with Node.js. It allows you to control your project’s dependencies and offers you an excellent way to contribute to the open-source world.

What is NPM?

NPM stands for Node Package Manager and is written in JavaScript that is considered to be the default package manager for Node.js. It was developed and maintained by Isaac Z. Schlueter on January 12, 2010. NPM helps manage all the Node.js packages, modules that come along with a command-line client called npm. Whenever you install Node.js, npm also gets installed with it. You can install the required packages and modules of Node.js using NPM.

A package comes with all the files that are needed for a module. These modules are the JavaScript libraries that you can include in the Node.js project as per the project requirement. You can install NPM dependencies for a project using the package.json file. It allows you to update and uninstall NPM packages if not required. If you consider the package.json file, each dependency has specified some range of valid NPM versions for which it will work through a semantic versioning scheme. It helps the developers to auto-update the packages along with avoiding unwanted breaking changes.

Npm helps manage the packages that are a local dependency of a specific project and for globally installed JavaScript tools. Npm not only manages the direct downloads but also manages the versioning. It allows you to install any version, either previous or later depending on your project requirement. If you do not mention any version to install, it will install the latest package version by default.

Below are some essential facts about NPM you should know.

What is the usage of NPM? (Node Package Manager)

Below is the common usage of npm:

Components of NPM

There are three main components of npm:

How to Install Node?

Below are some important commands that help in installing the npm. Before you update NPM version, we will go through the process of installing the npm.

However, npm comes as a part of Node.js, and you do not have to install it explicitly. If you want to install Node.js, you can navigate to the official site for the download. Once you install the Node, you can check the installed version of a node using the below commands.

How to Update NPM? (Node Package Manager)

If you want to update the NPM, it means you are updating the package manager, Node.js, and modules to the latest version.

Where g stands for global and pkg stands for the package.

1. Using Update Command

You can use the npm update command for updating the node package manager.

2. Using npm@latest Command

You can use the npm@latest command for updating the node package manager. This command will also work for the Linux system.

3. Using npm@next Command

You can use the npm@next command for updating the node package manager. This command will also work for the Linux system.

How to update NPM package on Linux?

1. Using PPA repository

You can run any of the below commands for updating the node package manager on the Linux system.

sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs npm

2. Using Cache Cleaning and Installing Stable NPM Version

Run all the following commands step-by-step to install the stable release.

How to update NPM version on Windows?

For updating npm, open the PowerShell with the admin account and run the following commands.

After running the commands, you will be asked to select an NPM version to install. You can use the arrow key to move upward and downward for selecting the version and hit enter.

If your upgrade process went successful, you would get the below output-

Conclusion

Node.js has become popular for creating interactive websites and web-based applications. It comes with npm (Node Package Manager) that helps manage the packages, modules, and dependencies of Node.js. You must use the latest stable NPM version for your products to experience the latest functionalities. Also, you know after reading this blog how to update NPM packages and how to update NPM version on any system, Windows, and Linux. You do not have to worry about installing npm explicitly as it comes with the Node.js installation.

In the above article, we have mentioned some commands that will help you to update the existing npm to the latest stable NPM version.

Try the latest stable version of npm

Table of contents

See what version of npm you’re running

Upgrading on *nix (OSX, Linux, etc.)

You can upgrade to the latest version of npm using:

Upgrading on Windows

By default, npm is installed alongside node in

C:\Program Files (x86)\nodejs

npm’s globally installed packages (including, potentially, npm itself) are stored separately in a user-specific directory (which is currently

Because the installer puts

C:\Program Files (x86)\nodejs

To get around this, you can do one of the following:

Option 2: remove both of

Option 3: Navigate to %ProgramFiles%\nodejs\node_modules\npm and copy the npmrc file to another folder or the desktop. Then open cmd.exe as an administrator and run the following commands:

If you installed npm with the node.js installer, after doing one of the previous steps, do the following.

A brief note on the built-in Windows configuration

The Node installer installs, directly into the npm folder, a special piece of Windows-specific configuration that tells npm where to install global packages. When npm is used to install itself, it is supposed to copy this special builtin configuration into the new install. There was a bug in some versions of npm that kept this from working, so you may need to go in and fix that up by hand. Run the following command to see where npm will install global packages to verify it is correct.

Incidentally, if you would prefer that packages not be installed to your roaming profile (because you have a quota on your shared network, or it makes logging in or out from a domain sluggish), you can put it in your local app data instead:

Everyone who works on npm knows that this process is complicated and fraught, and we’re working on making it simpler. Stay tuned.

Управление версиями Node.js и NPM с помощью NVM

Наш прошлый перевод про новые функции 15-й версии Node.js был очень хорошо принят читателями «Хабра», поэтому сегодня мы решили продолжить тему и рассказать, как настроить NVM с версией Node.js 15 и NPM 7.

Версия Node.js 15 была выпущена 20 октября 2020 года. Она поставляется с npm 7 и множеством новых функций. Вы уже успели опробовать новую версию?

Но подождите минутку! Node.js 15 и npm 7 содержат критические изменения. Не повредит ли тогда обновление существующим проектам?

Теоретически может повредить!

How to change npm version. Смотреть фото How to change npm version. Смотреть картинку How to change npm version. Картинка про How to change npm version. Фото How to change npm version

К счастью, у нас есть NVM (Node Version Manager), который избавит нас от этой опасности. Давайте детально рассмотрим данный инструмент, чтобы без проблем обновить версии node.js и npm.

Установка NVM

nvm управляет версиями node.js и npm. Он устанавливается для конкретного пользователя и может быть вызван отдельно для каждой оболочки. nvm работает с любой POSIX-совместимой оболочкой (sh, dash, ksh, zsh, bash), в том числе на платформах: unix, macOS и windows WSL.

nvm можно установить с помощью команд curl или wget:

Скрипт install.sh клонирует репозиторий nvm в

/.nvm и пытается добавить исходные строки из приведенного ниже фрагмента в нужный файл профиля (

/.bash_profile мы видим, что строки добавлены:

Использование NVM

Итак, мы установили nvm. Теперь используем данную команду для установки последней версии node.js:

Также мы можем указать нужную версию для установки. Семантический формат версии определяется SemVer:

Если указанная версия уже была установлена, она не переустанавливается:

Мы можем вывести на экран все установленные версии:

nvm use заменяет текущую версию:

Данная команда позволяет получить последнюю поддерживаемую версию npm для текущей версии Node.js:

nvm use устанавливает нужную версию только для текущей оболочки. Если вы измените оболочку, только что обновленная версия node.js будет потеряна.

Как сделать определенную версию Node.js постоянной?

Версия по умолчанию — такая версия, которая распространяется на все оболочки.

Команда nvm alias позволяет установить версию по умолчанию.

Мы можем проверить текущую версию с помощью следующей команды:

ls-remote выводит на экран все доступные версии, но будьте готовы к очень длинному списку.

Обратим внимание, что название версии в сокращенной форме значительно сокращает весь список.

Указанную версию Node.js можно использовать непосредственно для запуска приложений:

Если вам нужно больше nvm-команд, запустите команду help :

Обновление NVM

Обновляем до версии 0.37.2.

Как указано в выводе, нам нужно закрыть и снова открыть терминал, чтобы использовать новую версию:

How to change npm version. Смотреть фото How to change npm version. Смотреть картинку How to change npm version. Картинка про How to change npm version. Фото How to change npm version

По умолчанию nvm ls показывает следующие цвета:

How to change npm version. Смотреть фото How to change npm version. Смотреть картинку How to change npm version. Картинка про How to change npm version. Фото How to change npm version

Установим новые цвета:

nvm ls отображает вывод с новыми цветами:

How to change npm version

Node Version Manager How to change npm version. Смотреть фото How to change npm version. Смотреть картинку How to change npm version. Картинка про How to change npm version. Фото How to change npm version How to change npm version. Смотреть фото How to change npm version. Смотреть картинку How to change npm version. Картинка про How to change npm version. Фото How to change npm version

Table of Contents

nvm allows you to quickly install and use different versions of node via the command line.

Example:

nvm is a version manager for node.js, designed to be installed per-user, and invoked per-shell. nvm works on any POSIX-compliant shell (sh, dash, ksh, zsh, bash), in particular on these platforms: unix, macOS, and windows WSL.

Installing and Updating

Install & Update Script

To install or update nvm, you should run the install script. To do that, you may either download and run the script manually, or use the following cURL or Wget command:

Running either of the above commands downloads a script and runs it. The script clones the nvm repository to

Troubleshooting on Linux

These should pick up the nvm command.

Troubleshooting on macOS

Since OS X 10.9, /usr/bin/git has been preset by Xcode command line tools, which means we can’t properly detect if Git is installed or not. You need to manually install the Xcode command line tools before running the install script, otherwise, it’ll fail. (see #1782)

If you get nvm: command not found after running the install script, one of the following might be the reason:

/.zshrc and run the install script again.

/.bash_profile and run the install script again. Then, run source

/.bash_profile to pick up the nvm command.

If the above didn’t help, you might need to restart your terminal instance. Try opening a new tab/window in your terminal and retry.

If the above doesn’t fix the problem, you may try the following:

/.profile ) does not source your

/.bashrc properly. You could fix this by adding source

/ to it or follow the next step below.

Try adding the snippet from the install section, that finds the correct nvm directory and loads nvm, to your usual profile (

For more information about this issue and possible workarounds, please refer here

You can use a task:

To verify that nvm has been installed, do:

which should output nvm if the installation was successful. Please note that which nvm will not work, since nvm is a sourced shell function, not an executable binary.

If you’re running a system without prepackaged binary available, which means you’re going to install nodejs or io.js from its source code, you need to make sure your system has a C++ compiler. For OS X, Xcode will work, for Debian/Ubuntu based GNU/Linux, the build-essential and libssl-dev packages work.

Note: nvm also support Windows in some cases. It should work through WSL (Windows Subsystem for Linux) depending on the version of WSL. It should also work with GitBash (MSYS) or Cygwin. Otherwise, for Windows, a few alternatives exist, which are neither supported nor developed by us:

Note: nvm does not support Fish either (see #303). Alternatives exist, which are neither supported nor developed by us:

Note: We still have some problems with FreeBSD, because there is no official pre-built binary for FreeBSD, and building from source may need patches; see the issue ticket:

Note: On OS X, if you do not have Xcode installed and you do not wish to download the

Note: On OS X, if you have/had a «system» node installed and want to install modules globally, keep in mind that:

Note: If you’re using zsh you can easily install nvm as a zsh plugin. Install zsh-nvm and run nvm upgrade to upgrade.

Note: Git versions before v1.7 may face a problem of cloning nvm source from GitHub via https protocol, and there is also different behavior of git before v1.6, and git prior to v1.17.10 can not clone tags, so the minimum required git version is v1.7.10. If you are interested in the problem we mentioned here, please refer to GitHub’s HTTPS cloning errors article.

If you have git installed (requires git v1.7.10+):

Now add these lines to your

/.zshrc file to have it automatically sourced upon login: (you may have to add to more than one of the above files)

Now add these lines to your

/.zshrc file to have it automatically sourced upon login: (you may have to add to more than one of the above files)

For manual upgrade with git (requires git v1.7.10+):

To download, compile, and install the latest release of node, do this:

To install a specific version of node:

The first version installed becomes the default. New shells will start with the default version of node (e.g., nvm alias default ).

You can list available versions using ls-remote :

And then in any new shell just use the installed version:

Or you can just run it:

Or, you can run any arbitrary command in a subshell with the desired version of node:

You can also get the path to the executable to where it was installed:

To get the latest LTS version of node and migrate your existing installed packages, use

Migrating Global Packages While Installing

If you want to install a new version of Node.js and migrate npm packages from a previous version:

This will first use «nvm version node» to identify the current version you’re migrating packages from. Then it resolves the new version to install from the remote server and installs it. Lastly, it runs «nvm reinstall-packages» to reinstall the npm packages from your prior version of Node to the new one.

You can also install and migrate npm packages from specific versions of Node like this:

Note that reinstalling packages explicitly does not update the npm version — this is to ensure that npm isn’t accidentally upgraded to a broken version for the new node version.

or, you can at any time run the following command to get the latest supported npm version on the current node version:

Default Global Packages From File While Installing

If you want to install io.js:

If you want to install a new version of io.js and migrate npm packages from a previous version:

The same guidelines mentioned for migrating npm packages in node are applicable to io.js.

System Version of Node

If you want to use the system-installed version of node, you can use the special default alias «system»:

If you want to see what versions are installed:

If you want to see what versions are available to install:

Setting Custom Colors

You can set five colors that will be used to display version and alias information. These colors replace the default colors. Initial colors are: g b y r e

Persisting custom colors

If you want the custom colors to persist after terminating the shell, export the NVM_COLORS variable in your shell profile. For example, if you want to use cyan, magenta, green, bold red and bold yellow, add the following line:

Suppressing colorized output

To restore your PATH, you can deactivate it:

Set default node version

To set a default Node version to be used in any new shell, use the alias ‘default’:

Use a mirror of node binaries

For example, to make nvm default to the latest 5.9 release, the latest LTS version, or the latest node version for the current directory:

Then when you run nvm:

Deeper Shell Integration

You can use avn to deeply integrate into your shell and automatically invoke nvm when changing directories. avn is not supported by the nvm maintainers. Please report issues to the avn team.

If you prefer a lighter-weight solution, the recipes below have been contributed by nvm users. They are not supported by the nvm maintainers. We are, however, accepting pull requests for more examples.

Automatically call nvm use

This requires that you have bass installed.

Tests are written in Urchin. Install Urchin (and other dependencies) like so:

There are slow tests and fast tests. The slow tests do things like install node and check that the right versions are used. The fast tests fake this to test things like aliases and uninstalling. From the root of the nvm git repository, run the fast tests like this:

Run the slow tests like this:

Run all of the tests like this:

Nota bene: Avoid running nvm while the tests are running.

nvm exposes the following environment variables:

To activate, you need to source bash_completion :

How to use a specific version of NPM?

How can I switch which version of npm I’m using?

I tried but got an error:

Anyone know how to use a different version of NPM? Thanks

4 Answers 4

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Your NPM version is tied to your NodeJS version. As far as I can tell you can only have one NPM version per Node version. Using something like nodenv or, my favorite, asdf, you can define your node version per folder.

Per Node version (e.g. per folder) you globally install the version of NPM that you want to use.

How to change npm version. Смотреть фото How to change npm version. Смотреть картинку How to change npm version. Картинка про How to change npm version. Фото How to change npm version

You can update npm without installing another version of node.js and npm is not tied to versions of node.js specifically.

Of course, as node.js advances and adds features so too does npm so there is some limit for npm depending on node.js but you SHOULD update npm as much as you can because there are important security patches and bug fixes.

This is a best practice for all software. Stability is not worth ignoring a security risk.

Additionally you can install a specific version of npm to your package.json in a project like this npm install npm@6.14 and you can use it locally. What is even more interesting is you can install a local version of node.js in a project and use it too!

Example: I am running node 16.8.0 and I have npm 7.21.0 but I want to use an earlier version of npm but just for a project:

In the project directory

Since you have made this version of npm the one for this project, when you use npm in your scripts it will use 6.14.15 and not the global version.

The same is true of node.js.

If you do this, your project scripts in package.json scripts will run the locally installed versions rather than the global versions.

Then if you run npm run what:version you will get

What value is this?

It is a way for you to package node and npm with your project. This can be especially valuable for large projects where you have many people working on the same project, so you have consistency across the board or if you have a build server that has a specific version of node + npm. Additionally if you have corporate requirements, etc.

Additionally there is npx which allows you to do so much more. Using npx you can even try something out without installing it.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *