Npm how to delete package

Npm how to delete package

How to uninstall npm packages?

By Mario Kandut

Posted March 15, 2021

Updated June 19, 2022

Europe’s developer-focused job platform

Let companies apply to you

Developer-focused, salary and tech stack upfront.

Just one profile, no job applications!

💰 The Pragmatic Programmer: journey to mastery. 💰 One of the best books in software development, sold over 200,000 times.

To uninstall a package, you have to remove it from your node_modules folder (that’s where the code lives), and from package.json (listed there as a project dependency). If you only remove it in the node_modules folder and run npm install it will be reinstalled, and if you only remove the package entry in the package.json the package still exists in the node_modules folder.

But don’t worry. The npm uninstall command will do both of it. Follow these steps for uninstalling dependencies:

After successfully running the command, the NPM CLI will uninstall the package and print information to the terminal about how many packages were removed. Uninstalling removes the specified package, and all the packages it used internally as dependencies.

Uninstall global packages

Thanks for reading and if you have any questions, use the comment function or send me a message @mariokandut.

If you want to know more about Node, have a look at these Node Tutorials.

Adding and Removing Packages Using npm or Yarn

Npm how to delete package. Смотреть фото Npm how to delete package. Смотреть картинку Npm how to delete package. Картинка про Npm how to delete package. Фото Npm how to delete package

Npm how to delete package. Смотреть фото Npm how to delete package. Смотреть картинку Npm how to delete package. Картинка про Npm how to delete package. Фото Npm how to delete package

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

One of the beautiful things about both Open Source and the ecosystems of modern programming languages is that there’s a good chance the code you’re about to write has already been written.

There are a plethora of packages out there for Node.js and between you and me, they are usually written by folks smarter than myself that have thought through of a bunch of stuff I wouldn’t have even dreamed of. Standing on the shoulders of giants, as they say.

Getting started

For those new to the party, npm and yarn are package managers for Node.js. They both leverage the package.json file for your projects and function quite similarly.

Depending on your system, you could also consult with your friendly neighborhood package manager and install things that way.

Also, we’re going to be installing things globally as well as to a project as a dependency. You could very well use an existing project of yours, or you could create a dummy project out in your /tmp directory as such:

This creates a package.json file that we will be adding and removing packages from.

Adding a Development Dependency to a Project

Not all dependencies are created equal, as some are only required while doing development. These dependencies, while important, can slow down production deployments since they take time to install and the code will never be touched.

Adding a Production Dependency to a Project

Adding a production dependency to a project is just as easy as adding a development one, but it will be added to the dependencies section of our package.json instead:

Installing a Package Globally

Sometimes you want to install a package outside of your current project, so it’s available to all of the projects on your system. These are installed globally and are great for packages that also include command-line utilities that you want to run alongside your other command-line utilities:

Removing a Dependency From a Project

In every project’s life, there comes a time when a dependency that once seemed like a good idea, no longer serves any purpose. Don’t be too sad, deleting code is always a good thing (assuming you have proper test cover to ensure you didn’t break anything).

To remove either a development or production dependency from a project, we simply uninstall or remove it:

Uninstalling a Package Globally

Removing a globally installed package is the same as removing one from a project, but we need to pass in the global argument as we did when installing it:

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

How do I uninstall a package installed using npm link?

When installing a node package using sudo npm link in the package’s directory, how can I uninstall the package once I’m done with development?

npm link installs the package as a symbolic link in the system’s global package location (‘/usr/local/lib`). This allows you to test the package while still developing it, without having to install it over and over again.

Which npm command do I need to run to remove the link again?

8 Answers 8

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

In order to uninstall the globally linked foo package, the following command can be used (using sudo if necessary, depending on your setup and permissions)

This will uninstall the package.

To check whether a package is installed, the npm ls command can be used:

you can use unlink to remove the symlink.

To reinstall from your package.json:

npm link pain:

-Module name gulp-task

-Project name project-x

You want to link gulp-task:

1: Go to the gulp-task directory then do npm link this will symlink the project to your global modules

2: Go to your project project-x then do npm install make sure to remove the current node_modules directory

Now you want to remove this madness and use the real gulp-task, we have two options:

Option 1: Unlink via npm:

1: Go to your project and do npm unlink gulp-task this will remove the linked installed module

2: Go to the gulp-task directory and do npm unlink to remove symlink. Notice we didn’t use the name of the module

Option 2: Remove the symlink like a normal linux guru

1: locate your global dependencies cd /usr/local/lib/node_modules/

2: removing symlink is simply using the rm command

rm gulp-task make sure you don’t have / at the end

rm gulp-task/ is wrong 🔥🚨

Добавление и удаление пакетов с помощью npm или Yarn

Одна из лучших особенностей открытого кода и экосистем современных языков программирования заключается в том, что код, который вы собираетесь написать, вероятнее всего, уже написан и готов к использованию.

Для Node.js уже написано множество пакетов, и обычно эти пакеты созданы умными и опытными людьми, которые продумали кучу вещей, о которых менее опытный разработчик мог не подумать.

В этом мануале мы обсудим работу с инструментами npm и yarn. Обе эти команды довольно популярны, вы могли сталкиваться с ними в других статьях по Node.js. Если же вы никогда не слышали о них: npm и yarn – это менеджеры пакетов для Node.js. Оба они используют файл package.json и работают очень похожим образом.

Если у вас уже есть локальная установка Node.js, вероятно, у вас установлен и npm. Если вы предпочитаете использовать yarn, но у вас нет этой команды, вы можете ознакомиться с инструкциями по установке yarn здесь.

В зависимости от вашей системы вы также можете установить эти команды с помощью вашего менеджера пакетов.

Кроме того, некоторые пакеты мы будем устанавливать глобально, а другие – как зависимость проекта. Для работы с этим мануалом можно использовать уже существующий проект или создать простой тестовый проект в каталоге /tmp, например:

Эти команды создают файл package.json, в который мы будем добавлять и удалять пакеты.

Добавление зависимости разработки в проект

Не все зависимости одинаковы – некоторые из них требуются только при разработке. Эти зависимости тоже важны, но в производстве они могут замедлить развертывание, поскольку для их установки требуется время.

В качестве примера зависимостей разработки можно привести утилиты тестирования типа mocha или jest. Такие пакеты мы можем установить как зависимости разработки и добавить в раздел devDependencies нашего файла package.json:

Добавление зависимостей производства в проект

Некоторые зависимости критически важны для приложения и всегда должны устанавливаться независимо от среды – и в разработке, и в производстве без них никуда. Это зависимости производства, обычно к ним относятся такие пакеты, как express или react.

Добавить зависимость производства в проект так же просто, как и зависимости разработки, но вместо devDependencies их следует помещать ​​в раздел dependencies:

Глобальная установка зависимостей

Иногда бывает необходимо установить пакет вне текущего проекта, чтобы он был доступен для всех проектов в текущей системе. Такие пакеты устанавливаются глобально. Чаще всего они включают утилиты, которые необходимо запускать вместе с другими утилитами командной строки:

Удаление зависимости из проекта

В жизни каждого проекта наступает момент, когда зависимость, которая когда-то казалась жизненно необходимой, больше не выполняет никакой функции. В таком случае всегда лучше удалить код (при условии, что вы все хорошо протестировали и уверены, что после удаления ничего не сломается).

Чтобы удалить из проекта зависимость разработки или производства, используйте:

# NPM
$ npm uninstall jest
# Shorthand version
$ npm r jest
# Yarn
$ yarn remove jest

Это удалит пакеты из node_modules, а также уберет зависимость из package.json. Некоторые версии этих команд также показывают обновления файла.

Глобальное удаление пакета

Удаление глобально установленного пакета выполняется так же, как удаление пакета из проекта, только вы должны передать аргумент global (его же мы использовали при глобальной установке).

Getting Started with npm uninstall

Npm how to delete package. Смотреть фото Npm how to delete package. Смотреть картинку Npm how to delete package. Картинка про Npm how to delete package. Фото Npm how to delete package

With any well designed software, there must be a way to not only install the software, but to uninstall it from your machine. Node Package Manager, or npm, offers a simple command to achieve this. Using the npm uninstall command will uninstall the specific package either from the current project’s package.json file, or globally.

Most of the time, packages will be installed locally inside the current project’s directory. This means in order to install and uninstall these packages, you must change directories in the command line until you’re in the desired project. Uninstalling a global package can be done from any directory in the command line with a –global flag.

How to Use npm uninstall

Calling the npm uninstall command from the project’s directory will uninstall the package and remove the package from the project’s package.json file. As a review, a package.json file is a file, written in JSON that keeps track of the project’s packages. Removing a package from the file using npm uninstall will cause the project to stop using that package in the scope of the project.

Packages can locally or globally be installed. Most packages will be locally installed, meaning it is only available to the project in which it is installed. Globally installed packages are available to any project.

The npm package itself is an example of a global package. The command npm uninstall can be used in any project without having to install npm over again. Uninstalling packages can be done by calling the npm uninstall command followed by the package name.

Using this syntax in the command line will uninstall the package specified. Doing so will remove that package from the package.json folder of the current project. If any other project uses this package, it will not be affected.

npm uninstall accepts three optional flags:

Remember, these flags are optional. Most of the time, you’ll simply use the command followed by the package name alone.

81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.

Find Your Bootcamp Match

The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.

Start your career switch today

To uninstall a global package, use the –global or –g flag. Let’s say that you’ve been using React for years and want to use a different frontend library. To uninstall the create-react-app package from your computer completely, you’d use this command:

This will uninstall the package and remove anything npm installed on its behalf.

Conclusion

Using the npm uninstall command in your CLI is a safe and quick way to remove the package and anything else npm installed related to it. It provides a way to clean up any unused packages either inside a current project or from your entire computer. When uninstalling a package from your computer, don’t forget to use the –global or –g flag.

Including optional flags at the end of the uninstall command will remove the package only from those specific dependency files. This provides a little more control over uninstalling when needed. In general, using the simple syntax of npm uninstall

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

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

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