Npm install d что значит
Node Package Manager (npm) provides following two main functionalities: Online repositories for node.js packages/modules which are searchable on search.nodejs.org. Command line utility to install Node.js packages, do version management and dependency management of Node.js packages.
# Installing packages
# Introduction
Package is a term used by npm to denote tools that developers can use for their projects. This includes everything from libraries and frameworks such as jQuery and AngularJS to task runners such as Gulp.js. The packages will come in a folder typically called node_modules , which will also contain a package.json file. This file contains information regarding all the packages including any dependencies, which are additional modules needed to use a particular package.
Npm uses the command line to both install and manage packages, so users attempting to use npm should be familiar with basic commands on their operating system i.e.: traversing directories as well as being able to see the contents of directories.
# Installing NPM
Note that in order to install packages, you must have NPM installed.
The recommended way to install NPM is to use one of the installers from the Node.js download page
(opens new window) . You can check to see if you already have node.js installed by running either the npm -v or the npm version command.
After installing NPM via the Node.js installer, be sure to check for updates. This is because NPM gets updated more frequently than the Node.js installer. To check for updates run the following command:
# How to install packages
To install one or more packages use the following:
Note: This will install the package in the directory that the command line is currently in, thus it is important to check whether the appropriate directory has been chosen
If you already have a package.json file in your current working directory and dependencies are defined in it, then npm install will automatically resolve and install all dependencies listed in the file. You can also use the shorthand version of the npm install command which is: npm i
If you want to install a specific version of a package use:
If you want to install a version which matches a specific version range use:
If you want to install the latest version use:
The above commands will search for packages in the central npm repository at npmjs.com
(opens new window) . If you are not looking to install from the npm registry, other options are supported, such as:
Usually, modules will be installed locally in a folder named node_modules , which can be found in your current working directory. This is the directory require() will use to load modules in order to make them available to you.
If you already created a package.json file, you can use the —save (shorthand -S ) option or one of its variants to automatically add the installed package to your package.json as a dependency. If someone else installs your package, npm will automatically read dependencies from the package.json file and install the listed versions. Note that you can still add and manage your dependencies by editing the file later, so it’s usually a good idea to keep track of dependencies, for example using:
In order to install packages and save them only if they are needed for development, not for running them, not if they are needed for the application to run, follow the following command:
# Installing dependencies
Some modules do not only provide a library for you to use, but they also provide one or more binaries which are intended to be used via the command line. Although you can still install those packages locally, it is often preferred to install them globally so the command-line tools can be enabled. In that case, npm will automatically link the binaries to appropriate paths (e.g. /usr/local/bin/<name> ) so they can be used from the command line. To install a package globally, use:
If you want to see a list of all the installed packages and their associated versions in the current workspace, use:
Adding an optional name argument can check the version of a specific package.
Note: If you run into permission issues while trying to install an npm module globally, resist the temptation to issue a sudo npm install -g . to overcome the issue. Granting third-party scripts to run on your system with elevated privileges is dangerous. The permission issue might mean that you have an issue with the way npm itself was installed. If you’re interested in installing Node in sandboxed user environments, you might want to try using nvm
If you have build tools, or other development-only dependencies (e.g. Grunt), you might not want to have them bundled with the application you deploy. If that’s the case, you’ll want to have it as a development dependency, which is listed in the package.json under devDependencies . To install a package as a development-only dependency, use —save-dev (or -D ).
You will see that the package is then added to the devDependencies of your package.json .
To install dependencies of a downloaded/cloned node.js project, you can simply use
npm will automatically read the dependencies from package.json and install them.
# NPM Behind A Proxy Server
If your internet access is through a proxy server, you might need to modify npm install commands that access remote repositories. npm uses a configuration file which can be updated via command line:
You can locate your proxy settings from your browser’s settings panel. Once you have obtained the proxy settings (server URL, port, username and password); you need to configure your npm configurations as follows.
username , password , port fields are optional. Once you have set these, your npm install , npm i -g etc. would work properly.
# Uninstalling packages
To uninstall one or more locally installed packages, use:
The uninstall command for npm has five aliases that can also be used:
If you would like to remove the package from the package.json file as part of the uninstallation, use the —save flag (shorthand: -S ):
For a development dependency, use the —save-dev flag (shorthand: -D ):
For an optional dependency, use the —save-optional flag (shorthand: -O ):
For packages that are installed globally use the —global flag (shorthand: -g ):
# Setting up a package configuration
Node.js package configurations are contained in a file called package.json that you can find at the root of each project. You can setup a brand new configuration file by calling:
That will try to read the current working directory for Git repository information (if it exists) and environment variables to try and autocomplete some of the placeholder values for you. Otherwise, it will provide an input dialog for the basic options.
If you’d like to create a package.json with default values use:
If you’re creating a package.json for a project that you are not going to be publishing as an npm package (i.e. solely for the purpose of rounding up your dependencies), you can convey this intent in your package.json file:
- Optionally set the private property to true to prevent accidental publishing.
- Optionally set the license property to "UNLICENSED" to deny others the right to use your package.
To install a package and automatically save it to your package.json , use:
The package and associated metadata (such as the package version) will appear in your dependencies. If you save if as a development dependency (using —save-dev ), the package will instead appear in your devDependencies .
With this bare-bones package.json , you will encounter warning messages when installing or upgrading packages, telling you that you are missing a description and the repository field. While it is safe to ignore these messages, you can get rid of them by opening the package.json in any text editor and adding the following lines to the JSON object:
# Running scripts
You may define scripts in your package.json , for example:
To run the echo script, run npm run echo from the command line. Arbitrary scripts, such as echo above, have to be be run with npm run <script name> . npm also has a number of official scripts that it runs at certain stages of the package’s life (like preinstall ). See here
(opens new window) for the entire overview of how npm handles script fields.
npm scripts are used most often for things like starting a server, building the project, and running tests. Here’s a more realistic example:
In the scripts entries, command-line programs like mocha will work when installed either globally or locally. If the command-line entry does not exist in the system PATH, npm will also check your locally installed packages.
If your scripts become very long, they can be split into parts, like this:
# Basic semantic versioning
Before publishing a package you have to version it. npm supports semantic versioning
(opens new window) , this means there are patch, minor and major releases.
For example, if your package is at version 1.2.3 to change version you have to:
- patch release: npm version patch => 1.2.4
- minor release: npm version minor => 1.3.0
- major release: npm version major => 2.0.0
You can also specify a version directly with:
npm version 3.1.4 => 3.1.4
When you set a package version using one of the npm commands above, npm will modify the version field of the package.json file, commit it, and also create a new Git tag with the version prefixed with a "v", as if you’ve issued the command:
Unlike other package managers like Bower, the npm registry doesn’t rely on Git tags being created for every version. But, if you like using tags, you should remember to push the newly created tag after bumping the package version:
git push origin master (to push the change to package.json)
git push origin v3.1.4 (to push the new tag)
Or you can do this in one swoop with:
git push origin master —tags
# Publishing a package
First, make sure that you have configured your package (as said in Setting up a package configuration
(opens new window) ). Then, you have to be logged in to npmjs.
If you already have a npm user
If you don’t have a user
To check that your user is registered in the current client
After that, when your package is ready to be published use
And you are done.
If you need to publish a new version, ensure that you update your package version, as stated in Basic semantic versioning
(opens new window) . Otherwise, npm will not let you publish the package.
# Removing extraneous packages
To remove extraneous packages (packages that are installed but not in dependency list) run the following command:
To remove all dev packages add —production flag:
# Scopes and repositories
If the name of your own package starts with @myscope and the scope "myscope" is associated with a different repository, npm publish will upload your package to that repository instead.
You can also persist these settings in a .npmrc file:
This is useful when automating the build on a CI server f.e.
# Listing currently installed packages
To generate a list (tree view) of currently installed packages, use
ls, la and ll are aliases of list command. la and ll commands shows extended information like description and repository.
Options
The response format can be changed by passing options.
- json — Shows information in json format
- long — Shows extended information
- parseable — Shows parseable list instead of tree
- global — Shows globally installed packages
- depth — Maximum display depth of dependency tree
- dev/development — Shows devDependencies
- prod/production — Shows dependencies
If you want, you can also go to the package’s home page.
# Updating npm and packages
Since npm itself is a Node.js module, it can be updated using itself.
If OS is Windows must be running command prompt as Admin
If you want to check for updated versions you can do:
In order to update a specific package:
This will update the package to the latest version according to the restrictions in package.json
In case you also want to lock the updated version in package.json:
# Locking modules to specific versions
By default, npm installs the latest available version of modules according to each dependencies’ semantic version
(opens new window) . This can be problematic if a module author doesn’t adhere to semver and introduces breaking changes in a module update, for example.
To lock down each dependencies’ version (and the versions of their dependencies, etc) to the specific version installed locally in the node_modules folder, use
This will then create a npm-shrinkwrap.json alongside your package.json which lists the specific versions of dependancies.
# Setting up for globally installed packages
You can use npm install -g to install a package "globally." This is typically done to install an executable that you can add to your path to run. For example:
If you update your path, you can call gulp directly.
On many OSes, npm install -g will attempt to write to a directory that your user may not be able to write to such as /usr/bin . You should not use sudo npm install in this case since there is a possible security risk of running arbitrary scripts with sudo and the root user may create directories in your home that you cannot write to which makes future installations more difficult.
You can tell npm where to install global modules to via your configuration file,
/.npmrc . This is called the prefix which you can view with npm prefix .
This will use the prefix whenever you run npm install -g . You can also use npm install —prefix
/.npm-global-modules to set the prefix when you install. If the prefix is the same as your configuration, you don’t need to use -g .
In order to use the globally installed module, it needs to be on your path:
Now when you run npm install -g gulp-cli you will be able to use gulp .
Note: When you npm install (without -g ) the prefix will be the directory with package.json or the current directory if none is found in the hierarchy. This also creates a directory node_modules/.bin that has the executables. If you want to use an executable that is specific to a project, it’s not necessary to use npm install -g . You can use the one in node_modules/.bin .
# Linking projects for faster debugging and development
Building project dependencies can sometimes be a tedious task. Instead of publishing a package version to NPM and installing the dependency to test the changes, use npm link . npm link creates a symlink so the latest code can be tested in a local environment. This makes testing global tools and project dependencies easier by allowing the latest code run before making a published version.
# Help text
# Steps for linking project dependencies
When creating the dependency link, note that the package name is what is going to be referenced in the parent project.
- CD into a dependency directory (ex: cd ../my-dep )
- npm link
- CD into the project that is going to use the dependency
- npm link my-dep or if namespaced npm link @namespace/my-dep
# Steps for linking a global tool
- CD into the project directory (ex: cd eslint-watch )
- npm link
- Use the tool
- esw —quiet
# Problems that may arise
Linking projects can sometimes cause issues if the dependency or global tool is already installed. npm uninstall (-g) <pkg> and then running npm link normally resolves any issues that may arise.
What does npm -D flag mean?
I am about to install this npm package and it says npm install -D load-grunt-config . What does the -D flag do?
![]()
2 Answers 2
The -D flag is the shortcut for: —save-dev . Source: https://docs.npmjs.com/cli/install
-D, —save-dev: Package will appear in your devDependencies.
![]()
As described in the NPM Install Docs:
-D, —save-dev : Package will appear in your devDependencies.
Which means that the package will not be installed if you do npm install —production .
Creating development dependencies with npm install -D command
Sometimes, you may see the npm install command paired with -D or —save-dev flag as follows:
The -d flag will record the npm package you just installed to your project as a development dependency under the devDependencies property in your package.json file:
The difference between dependencies and devDependencies is that packages listed under dependencies are required for running the project without any error, while packages registered as devDependencies are needed for developing the project further.
For example, when you install the axios package to your project, the package follow-redirects will also be installed in your node_modules/ folder because it’s recorded as a dependency in Axios’s dependencies property:
When you open Axios’ package.json file, you will also see a many packages recorded under the devDependencies property:
But you won’t find these packages installed inside the node_modules/ folder. This is because the packages are only required for development.
The packages listed under devDependencies will only be installed when you clone the project and run npm install for that project.
To conclude, the —save-dev or -D flag is used to install a package as a development dependency. You need to make sure that the dependency is not required for running the project seamlessly.
Packages added as devDependencies are usually task runners like Grunt or Gulp, test frameworks like Jest or Karma, or build tools like Rollup or Webpack.
Take your skills to the next level ⚡️
I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!
report this ad
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Как использовать ключи -save-exact и -save-dev
Вы рекомендовали использовать ключи -DE, в статье просто -D, в документации:
Объясните, что делают различные флаги при установке пакетов -D -de -save-dev? Чем они отличаются? Что по факту делает этот флаг? Что будет если его не поставить при установке пакета?
Для обновления пакетов мы используем ключи -DE (их следует писать прописными). Это сокращённая запись.
D — псевдоним для -save-dev . Когда мы используем D , то подразумеваем, что пакет должен быть установлен в devDependencies (зависимости для разработки).
E — псевдоним для -save-exact . С помощью этого параметра фиксируем версию. Если им не воспользоваться, то рядом с версией пакета в package.json появится «крышечка», символ ^ .
Вот и получается, что указание -DE равносильно применению —save-dev и —save-exact . Разницы нет никакой. Просто запись короче и проще запомнить, но это вкусовщина. Каждый делает, как нравится.
Что за символ ^
Если мы установим любой пакет вот так (без фиксации версии):
то в package.json получим что-то вроде этого:
Представим, что мы захотели обновить версию пакета. Для этого в npm предусмотрена отдельная команда:
До какой версии будет обновлён пакет eslint — до самой свежей или нет?
Семантическое версионирование
Чтобы ответить, посмотрим, из чего строится номер версии (например, 7.0.1 ). Для нумерации применяется семантическое версионирование SEMVER. Оно работает так:
Мажорный номер версии — 7. Он меняется в важных случаях — например, когда теряется обратная совместимость с прошлой версией, добавлено или удалено новое API и так далее.
Минорный номер версии — 0. Меняется, когда добавляются новые возможности без потери обратной совместимости.
Патч версия — 1. Изменяется, когда вносятся баг-фиксы или мелкие улучшения, не добавляющие новую функциональность и не влияющие на обратную совместимость.
Дополнительные символы нужны, чтобы задать критерий обновления:
-
^ (крышечка) — совместимость на уровне мажорной-версии. Пакет может быть обновлён до максимально свежей версии в пределах текущей мажорной.
При установке новых пакетов npm по умолчанию для всех пакетов добавляет символ «крышечки», то есть фиксирует совместимость на уровне мажорной версии. Поэтому при обновлении мы можем беспрепятственно получать свежие версии и случайно не перепрыгнуть на следующую мажорную версию, где может измениться API и проект перестанет корректно работать.
Теоретически всё здорово, но при условии, что мы живём в идеальном мире. Не все разработчики придерживаются правил семантического версионирования и запросто может произойти ситуация, когда изменения в пределах мажорной версии могут что-то сломать.
Чтобы не столкнуться с такой ситуацией, мы фиксируем номер версии, то есть в package.json не должно быть дополнительных символов ^ и
Для этого мы и применяем параметр —save-exact или его алиас ( -E ).
Другие материалы
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
Читать дальше

Случайное число из диапазона
Допустим, вам зачем-то нужно целое случайное число от min до max . Вот сниппет, который поможет:
- Math.random () генерирует случайное число между 0 и 1. Например, нам выпало число 0.54 .
- (max — min + 1): определяет количество возможных значений в заданном диапазоне. 10 — 0 + 1 = 11 . Это значит, что у нас есть 11 возможных значений (0, 1, 2, . 10).
- Math.random () * (max — min + 1): умножает случайное число на количество возможных значений: 0.54 * 11 = 5.94 .
- Math.floor (): округляет число вниз до ближайшего целого. Так, Math.floor(5.94) = 5 .
- . + min: смещает диапазон так, чтобы минимальное значение соответствовало min . Но в нашем примере, так как min = 0 , это не изменит результат. Пример: 5 + 0 = 5 .
- Итак, в нашем примере получилось случайное число 5 из диапазона от 0 до 10.
Чтобы протестировать, запустите:
- 7 сентября 2023

В чём разница между var и let
Если вы недавно пишете на JavaScript, то наверняка задавались вопросом, чем отличаются var и let , и что выбрать в каждом случае. Объясняем.
var и let — это просто два способа объявить переменную. Вот так:
Переменная, объявленная через var , доступна только внутри «своей» функции, или глобально, если она была объявлена вне функции.
Это может создавать неожиданные ситуации. Допустим, вы создаёте цикл в функции и хотите, чтобы переменная i осталась в этой функции. Если вы используете var , эта переменная «утечёт» за пределы цикла и будет доступна во всей функции.
Переменные, объявленные с помощью let доступны только в пределах блока кода, в котором они были объявлены.
В JavaScript блок кода — это участок кода, заключённый в фигурные скобки <> . Это может быть цикл, код в условном операторе или что-нибудь ещё.
Если переменная j объявлена в цикле с let , она останется только в этом цикле, и попытка обратиться к ней за его пределами вызовет ошибку.
- 30 августа 2023

Быстрый гайд по if, else, else if в JavaScript
Допустим, вы собираетесь идти на прогулку. Если на улице солнечно, вы возьмёте с собой солнечные очки.
Это можно описать с помощью оператора if .
А если погода не солнечная, а, скажем, дождливая, вы возьмете зонт.
Этот сценарий можно описать с помощью if-else .
Условный оператор if-else if-else
Теперь представим, что у вас есть несколько вариантов транспорта для дороги на работу: машина, велосипед, общественный транспорт. Выбор будет зависеть от различных условий, например, погоды и времени суток. Логично, что в дождь безопаснее ехать на автобусе, а в хорошую погоду можно прокатиться на машине или велосипеде, если утро и пробки. То есть схема такая:
И всё это очень легко описывается кодом:
Ветвление только может показаться сложным, но вообще оно очень логичное, если понять, какие действия после каких условий выполняются. Разберитесь один раз и поймёте на всю жизнь, 100%.
- 30 августа 2023

Как исправить ошибки SyntaxError в JavaScript
Ошибки SyntaxError появляются, если разработчик нарушил правила синтаксиса JavaScript, например, пропустил закрывающую скобку или точку с запятой. Давайте посмотрим, что означает каждая ошибка и в чём может быть проблема.
- 14 июля 2023

Ошибка TypeError: что это и как её исправить
Ошибки TypeError появляются, когда разработчики пытаются выполнить операцию с неправильным типом данных. Давайте разберём несколько примеров: почему появилась ошибка и как её исправить.
- 7 июля 2023

3 способа объявить функцию в JavaScript
Функции в JavaScript можно объявить тремя способами: через декларативное объявление, функциональное выражение или с помощью стрелок. Звучит сложно, но на самом деле всё совсем не так.
- 30 июня 2023

Как сделать простой слайдер на HTML и JavaScript
Вы сверстали сайт и сделали его красивым с помощью CSS. Осталось добавить интерактива, и можно добавлять проект в портфолио.
«Оживить» на сайте можно что угодно: меню, модальные окна, корзину, пагинацию… В этой статье мы разберём слайдер — посмотрим, как его сделать на чистом JavaScript. Слайдер пригодится для раздела с отзывами, фотографиями сотрудников, изображениями товаров или чего-нибудь ещё — всё зависит только от вашей фантазии и проекта.
☝ Мы покажем лишь один из возможных вариантов. Это не эталонное решение, да в разработке и не бывает единственно верного способа решить задачу. Но код точно работает, поэтому можете скопировать его в свой проект.
- 20 июня 2023

Полезные команды для работы с Node.js
Перед тем как рассматривать полезные команды при работе с Node.js, её необходимо установить.
Команды помогают узнать версию Node.js,
node -h — показывает список всех доступных команд Node.js.
node -v , node —version — показывает установленную версию Node.js.
npm -h — показывает список всех доступных команд пакетного менеджера npm .
npm -v , npm —version — показывает установленную версию npm .
Команда npm update npm -g позволяет обновить версию npm .
npm list —depth=0 показывает список установленных пакетов.
Команда npm outdated —depth=0 покажет список установленных пакетов, которые требуют обновления. Если все пакеты обновлены, список будет пустым.
npm install package — позволяет установить любой пакет по его имени. Если при этом к команде добавить префикс -g пакет будет установлен глобально на весь компьютер.
Команда npm i package является укороченной альтернативой предыдущей команды.
Если вы хотите установить конкретную версию пакета, воспользуйтесь префиксом @ с номером версии. Например, npm install package@1.0.1 .
npm uninstall package — удаляет установленный пакет по имени.
Команда npm list package — покажет версию установленного пакета, а команда npm view package version — последнюю версию пакета, которая существует.
Для работы с пакетным менеджером также пригодится файл package.json , который должен лежать в директории, с которой происходит работа в консоли.
Он содержит различные мета-данные, например, имя проекта, версия, описания и автор. Также он содержит список зависимостей, которые будут установлены, если вызвать из этой папки команду npm install .
Кроме этого он ещё имеет скрипты, которые вызывают другие команды консоли. Например, для этого файла вызов команды npm start вызовет запуск задачи Grunt с именем dev . А команда npm run build вызовет скрипт build , который запустит задачу в Grunt с именем build .
Во время работы часто возникает необходимость установить некоторые пакеты. Если установить пакет с префиксом —save , то он автоматически запишется в package.json в раздел dependencies . Такая же команда с префиксом —save-dev запишет пакет в раздел devDependencies .
nvm (илиNode Version Manager) — утилита, которая позволяет быстро менять версии Node.js.
Чтобы её установить, достаточно запустить скрипт
Теперь можно установить последнюю версию Node.js, например, 5.0 с помощью команды nvm install 5.0 . Чтобы начать использовать её, введите команду nvm use 5.0 . Таким образом, можно быстро переключаться между версиями, например, для тестирования.
- 8 июня 2023

Как составлять регулярные выражения
Регулярное выражение — это последовательность символов (селекторов). Оно используется для поиска и обработки строк, слов, чисел и других текстовых данных.
Регулярные выражения выручают при решении разных задач. Например, с их помощью легко искать и менять строки в коде. Но чаще всего регулярные выражения используют для валидации форм. Давайте посмотрим, как это делать.
- 5 июня 2023

Проверка типа интерфейса в TypeScript
Проверка типов интерфейса — одна из ключевых возможностей TypeScript. Она помогает убедиться, что объект или класс содержат необходимый набор свойств и методов, указанных в интерфейсе. Благодаря проверке типов вы можете писать более надёжный код, ведь часть ошибок будет найдена ещё на этапе компиляции.