Как установить зависимости из package json
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.
if0rest / npm.md
Флаг —save-dev или -D позволяет установить пакет и добавить запись о нём в раздел, содержащий перечень зависимостей разработки (то есть — пакетов, которые нужны в ходе разработки проекта, вроде библиотек для тестирования, но не требуются для его работы) файла package.json, который называется devDependencies.
- dependencies — содержит список npm-пакетов, от которых зависит приложение.
- devDependencies — содержит список npm-пакетов, используемых при разработке проекта, но не при его реальной работе.
Ключ -g говорит о том, что пакет установится в систему глобально, то-есть в систему, а не в папку проекта.
Файл package.json является файлом манифеста нашего проекта, который описывает помимо той информации, что мы внесли в терминале, еще и информацию об используемых пакетах в нашем проекте.
Например, если мы установим в проект Gulp с ключом —save-dev, то пакет и используемая версия автоматически добавится в наш package.json. Такой учет позволит быстро разворачивать новый проект с использованием уже имеющегося package.json и устанавливать необходимые модули с зависимостями, которые прописаны в package.json в новых проектах.
Получив эту команду, npm проверит все пакеты на наличие их новых версий, и, если найдёт их новые версии, соответствующие ограничениям на версии пакетов, заданным в package.json, установит их.
Даже если, следуя правилам семантического версионирования, минорные релизы и патч-релизы не должны содержать в себе изменений, препятствующих обратной совместимости, все мы знаем, что ошибки способны проникать (и проникают) куда угодно.
ВЫЯСНЕНИЕ ВЕРСИЙ УСТАНОВЛЕННЫХ NPM-ПАКЕТОВ
Узнать версии всех установленных в папке проекта npm-пакетов, включая их зависимости:
То же самое можно узнать и просмотрев файл package-lock.json проекта, но древовидную структуру, которую выводит вышеописанная команда, удобнее просматривать.
Вывести только сведения о локальных пакетах верхнего уровня (которые устанавливали самостоятельно и которые перечислены в package.json):
npm list —depth=0
Узнать версию конкретного пакета:
npm list cowsay
Узнать номер самой свежей версии некоего пакета, доступного в npm-репозитории:
npm view <package> version
Узнать, какие версии некоего пакета имеются в npm:
npm view <package> versions
Узнать, вышли ли новые версии используемых пакетов:
УСТАНОВКА СТАРЫХ ВЕРСИЙ NPM-ПАКЕТОВ
Установить нужную версию пакета из npm можно, воспользовавшись следующей конструкцией:
npm install <package>@<version>
Указывать версии можно и устанавливая глобальные пакеты:
npm install -g webpack@4.16.4
Когда вы устанавливаете пакет командой вида npm install <packagename> , из репозитория загружается самая свежая из доступных версий и помещается в папку node_modules. При этом соответствующие записи добавляются в файлы package.json и package-lock.json, находящиеся в папке проекта.
Правило обновления пакета в виде ^1.3.1 означает, что npm может обновлять пакет при выходе его минорных и патч-версий.
АНАЛИЗ УСТАРЕВШИХ ЗАВИСИМОСТЕЙ ПРОЕКТА
Некоторые из доступных обновлений пакетов представляют собой их мажорные релизы, обновления до которых не произойдёт при выполнении команды npm update. Обновление до мажорных релизов этой командой не производится, так как они (по определению) могут содержать серьёзные изменения, не отличающиеся обратной совместимостью с предыдущими мажорными релизами. Для того чтобы обновиться до новых мажорных версий всех используемых пакетов, глобально установите пакет npm-check-updates :
npm install -g npm-check-updates
Затем запустите утилиту, предоставляемую им:
Эта команда обновит файл package.json, внеся изменения в указания о подходящих версиях пакетов в разделы dependencies и devDependencies. Это позволит npm обновить пакеты, используемые в проекте, до новых мажорных версий после запуска команды npm update . Если вы хотите установить самые свежие версии пакетов для только что только что загруженного проекта, в котором пока нет папки node_modules, то, вместо npm update , выполните команду npm install .
КАКОЙ СПОСОБ УСТАНОВКИ ПАКЕТОВ ЛУЧШЕ ИСПОЛЬЗОВАТЬ: ЛОКАЛЬНЫЙ ИЛИ ГЛОБАЛЬНЫЙ?
В общем случае, все пакеты следует устанавливать локально. Благодаря этому, даже если у вас имеются десятки nodejs-проектов, можно обеспечить, при необходимости, использование ими различных версий одних и тех же пакетов. Обновление глобального пакета приводит к тому, что все проекты, в которых он применяется, будут использовать его новый релиз. Несложно понять, что это, в плане поддержки проектов, может привести к настоящему кошмару, так как новые релизы некоторых пакетов могут оказаться несовместимыми с их старыми версиями.
Пакеты следует устанавливать глобально, когда они представляют собой некие утилиты, вызываемые из командной строки, которые используются во множестве проектов. Подобные пакеты можно устанавливать и локально, запуская предоставляемые ими утилиты командной строки с использованием npx, но некоторые пакеты, всё же, лучше устанавливать глобально. Например, следующие:
- npm
- create-react-app
- vue-cli
- grunt-cli
- mocha
- react-native-cli
- gatsby-cli
- forever
- nodemon
Не исключено, что в вашей системе уже имеются пакеты, установленные глобально. Для того чтобы об этом узнать, воспользуйтесь следующей командой:
npm list -g —depth 0
О ЗАВИСИМОСТЯХ ПРОЕКТОВ
Когда пакет следует рассматривать как обычную зависимость проекта, необходимую для обеспечения его функционирования, а когда — как зависимость разработки?
При установке пакета с помощью команды вида npm install <package-name> он устанавливается как обычная зависимость. Запись о таком пакете делается в разделе dependencies файла package.json. Использование флага —save-dev позволяет установить пакет как зависимость разработки. Запись о нём при этом делается в разделе devDependencies файла package.json. Зависимости разработки — это пакеты, которые нужны в процессе разработки проекта, в ходе его обычного функционирования они не требуются. К таким пакетам относятся, например инструменты тестирования, Webpack, Babel. Когда проект разворачивают, используя команду npm install в его папке, в которой имеется папка, содержащая файл package.json, это приведёт к установке всех зависимостей, так как npm предполагает, что подобная установка выполняется для целей работы над проектом. Поэтому, если пакет требуется развернуть в продакшне, то, при его развёртывании, нужно использовать команду npm install —production Благодаря флагу —production зависимости разработки устанавливаться не будут.
Сейчас мы поговорим об одной весьма мощной команде, npx , которая появилась в npm 5.2. Одной из её возможностей является запуск исполняемых файлов, входящих в состав npm-пакетов. Мы уже рассматривали использование npx для запуска подобного файла из пакета cowsay. Теперь поговорим об этом подробнее.
How to install npm packages?
This article is based on Node v16.15.1 and NPM 8.11.0.
Installing dependencies is a core part of working with any Node.js project. If you are just starting with Node.js, have a look at this article — how to uninstall npm packages.
The Pragmatic Programmer: journey to mastery. One of the best books in software development, sold over 200,000 times.
Before an application can run, you need to install all existing dependencies from the package.json file. You can also add new packages as dependencies or devDependencies.
Installing dependencies from package.json
The most common way to interact with the npm CLI is through installing packages with npm install <package> command from npmjs.com. When you check out a new project repository and try to start the application with npm start , you will likely get this error — Error: Cannot find module . This means, you forgot to install the project’s dependencies.
To install a project’s dependencies, navigate in the root folder of the application, and run:
You’ll see a progress bar as npm begins downloading the dependencies, and a node_modules/ folder will be created in the project’s root directory. A package-lock.json file will also be created, if none existed in the project already. Check out the article — What is package-lock.json, if you are not familiar with this file.
Basically running npm install (with no arguments) reads the list of dependencies from the package.json with the applicable package versions and version locks( package-lock.json ), downloads the dependencies, and puts them into the node_modules/ folder. Once the dependencies are added into the node_modules folder, they are found by the application.
Most npm commands have an alias, so you don’t have to type the entire command. Just type npm i and npm install will be executed.
Installing new dependencies
The command npm install can also be used to add new dependencies. You can find packages on npmjs.com. Just run npm install <package-name> to add the new dependency. For example, to install the popular Express server framework as a dependency:
After running the command npm install express , you will see a progress bar as npm fetches the package. The package will be downloaded from NPM, installed to your node_modules/ folder, and added to the dependencies in package.json . The package-lock.json file also updated, which will happen whenever you add or update dependencies. If express is added to a fresh package.json, after npm init , the package.json might look like this:
Install new devDependency
When installing a package we can choose to record it in the package.json as an entry to dependencies or devDependencies. You can learn more about the difference between dependencies and devDependencies in the article — what is package.json. To sum up, dependencies are used during production, and devDependencies are used only in development or during a build step.
By default, npm install adds the package as an entry to dependencies , when the flag —save-dev , or it’s alias -D , is added, the package will be installed as a devDependency . ESLint would be a typical devDependency.
After running this command, an entry should be added to devDependencies in the package.json:
You can also install packages globally. This will be covered in a separate article, since there can be errors, like EACCES , and npx is a great addition to run an arbitrary command from an NPM package. Maybe you don’t need to install a package globally, since it can only be used with one installed Node.js version (another Node.js version, would require a new global install).
- Installing dependencies is a core part of working with any Node.js project.
- Install the project dependencies listed in the package.json with npm install .
- Some NPM cli commands have an alias ( npm i for npm install ).
- Install a new dependency with npm install <package> .
- Install a new devDependency by passing the flag —save-dev , like npm install <package> —save-dev .
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.
Как установить зависимости из package json
Кроме встроенных и кастомных модулей Node.js существует огромный пласт различных библиотек и фреймворков, разнообразных утилит, которые создаются сторонними производителями и которые также можно использовать в проекте, например, express, grunt, gulp и так далее. И они тоже нам доступны в рамках Node.js. Чтобы удобнее было работать со всеми сторонними решениями, они распространяются в виде пакетов. Пакет по сути представляет набор функциональностей.
Для автоматизации установки и обновления пакетов, как правило, применяются систему управления пакетами или менеджеры. Непосредственно в Node.js для этой цели используется пакетный менеджер NPM (Node Package Manager). NPM по умолчанию устанавливается вместе с Node.js, поэтому ничего доустанавливать не требуется. Но можно обновить установленную версию до самой последней. Для этого в командной строке/терминале надо запустить следующую команду:
Чтобы узнать текущую версию npm, в командной строке/терминале надо ввести следующую команду:
Для нас менеджер npm важен в том плане, что с его помощью легко управлять пакетами. К примеру, создадим на жестком диске новую папку modulesapp (В моем случае папка будет находиться по пути C:\node\modulesapp ).
Если в дальнейшем нам больше не потребуется express, то мы его можем удалить следующей командой:
Файл package.json
Для более удобного управления конфигурацией и пакетами приложения в npm применяется файл конфигурации package.json . Так, добавим в папку проекта modulesapp новый файл package.json :
Здесь определены только две секции: имя проекта — modulesapp и его версия — 1.0.0. Это минимально необходимое определение файла package.json. Данный файл может включать гораздо больше секций. Подробнее можно посмотреть в документации.
Далее для примера установим в проект express . Express представляет легковесный веб-фреймворк для упрощения работы с Node.js. В данном случае мы не будем пока подробно рассматривать фреймворк Express, так как это отдельная большая тема. А используем его лишь для того, чтобы понять, как устанавливаются сторонние модули в проект.
Для установки функциональности Express в проект вначале перейдем к папке проекта с помощью команды cd . Затем введем команду

После установки express в папке проекта modulesapp появится подпапка node_modules , в которой будут хранится все установленные внешние модули. В частности, в подкаталоге node_modules/express будут располагаться файлы фреймворка Express.
И после выполнения команды, если мы откроем файл package.json , то мы увидим информацию о пакете:
Информация обо всех добавляемых пакетах, которые используются при работе приложения, добавляется в секцию dependencies .
Используем добавленный пакет express и для этого определим файл простейшего сервера. Для этого в корневую папку проекта modulesapp добавим новый файл app.js :
Первая строка получает установленный модуль express, а вторая создает объект приложения.
В Express мы можем связать обработку запросов с определенными маршрутами. Например, «/» — представляет главную страницу или корневой маршрут. Для обработки запроса вызывается функция app.get() . Первый параметр функции — маршрут, а второй — функция, которая будет обрабатывать запрос по этому маршруту.
И чтобы сервер начал прослушивать подключения, надо вызвать метод app.listen() , в который передается номер порта.
Запустим сервер командой node app.js :

И в адресной строке браузера введем адрес http://localhost:3000/ :

Добавление множества пакетов
Файл package.json играет большую роль и может облегчить работу с пакетами в различных ситуациях. Например, мы планируем использовать множество пакетов. Но вводить для установки каждого пакета в консоли соответствующую команду не очнь удобно. В этом случае мы можем определить все пакеты в файле package.json и потом одной командой их установить.
Например, изменим файл package.json следующим образом:
Здесь добавлены определения двух пакетов, которые представляют библиотеку React.
Затем для загрузки всех пакетов выполнить команду
Эта команда возьмет определение всех пакетов из секций dependencies и загрузит их в проект. Если пакет с нужной версией уже есть проекте, как в данном случае express, то по новой он не загружается.
devDependencies
Кроме пакетов, которые применяются в приложении, когда оно запущено и находится в рабочем состояни, например, express, то есть в состоянии «production», есть еще пакеты, которые применяются при разработке приложения и его тестировании. Такие пакеты, как правило, добавляются в другую секцию — devDependencies .
Например, загрузим в проект пакет jasmine-node , который используется для тестирования приложения:
Флаг —save-dev указывается, что информацию о пакете следует сохранить именно в секции devDependencies файла package.json:
Удаление пакетов
Для удаления пакетов используется команда npm uninstall . Например:
При этом не важно, где располагается информация о пакете — в секции dependencies или devDependencies, пакет удаляется из любой из этих секций.
Если нам надо удалить не один пакет, а несколько, то мы можем удалить их определение из файла package.json и ввести команду npm install , и удаленые из package.js пакеты также будут удалены из папки node_modules.
Например, изменим файл package.json следующим образом:
Здесь больше нет определения никаких пакетов. И введем команду
Причем мы также можем одновременно некоторые пакеты добавлять в package.json, а некоторые, наоборот, удалять. И при выполнении команды npm install пакетный менеджер новые пакеты установит, а удаленные из package.json пакеты удалит.
Семантическое версионирование
При определении версии пакета применяется семантическое версионирование. Номер версии, как правило, задается в следующем формате «major.minor.patch». Если в приложении или пакете обнаружен какой-то баг и он исправляется, то увеличивается на единицу число «patch». Если в пакет добавляется какая-то новая функциональность, которая совместима с предыдущей версией пакета, то это небольшое изменение, и увеличивается число «minor». Если же в пакет вносятся какие-то большие изменения, которые несовместимы с предыдущей версией, то увеличивается число «major». То есть глядя на разные версии пакетов, мы можем предположить, насколько велики в них различия.
В примере с express версия пакета содержала, кроме того, дополнительный символ карет: «^4.14.0». Этот символ означает, что при установке пакета в проект с помощью команды npm install будет устанавливаться последняя доступная версия от 4.14.0. Фактически это будет последняя доступная версия в промежутке от 4.14.0 до 5.0.0 (>=4.14.0 и <5.0.0).
Команды npm
NPM позволяет определять в файле package.json команды, которые выполняют определенные действия. Например, определим следующий файл app.js :
В данном случае мы получаем переданные при запуске приложению параметры.
И определим следующий файл package.json :
Здесь добавлена секция scripts , которая определяет две команды. Вообще команд может быть много в соответствии с целями и задачами разработчика.
Первая команда называется start . Она по сути выполняет команду node app.js , которая выполняет код в файле app.js
Вторая команда назвывается dev . Она также выполняет тот же файл, но при этом также передает ему два параметра.
Названия команд могут быть произвольными. Но здесь надо учитывать один момент. Есть условно говоря есть зарезервированные названия для команд, например, start , test , run и ряд других. Их не очень много. И как раз первая команда из выше определенного файла package.json называется start. И для выполнения подобных команд в терминале/командной строке надо выполнить команду
Например, для запуска команды start
Команды с остальными названия, как например, «dev» в вышеопределенном файле, запускаются так: