I want to graduate from npm install properly [2020]

Introduction

I didn't understand the command npm install in the articles on the internet, but I wanted to graduate from that state, so I posted this article as a memorandum.

I'll mainly talk about the npm install command, but I'd also like to touch on some basic things about npm, such as package.json and node_modules.

Purpose

The purpose of this article is to help you understand what happens when you run the following four npm install commands and to use these four commands according to your needs.

In other words, graduate from doing npm install properly.

Operating environment

# Node.js version check
$ node -v
v14.13.1

#npm version check
$ npm -v
6.14.8

By the way, the update of npm itself is the following command. You should also be aware of the npm version of the article you refer to, as npm behaves quite differently in different major versions.

#npm update
$ npm update -g npm

What you need to know before explaining npm install

If you don't understand this area, you will end up doing npm install properly, so I will explain it first. If you know it, you can skip it.

Node.js Node.js is JavaScript that runs on the server side.

npm npm (Node Package Manager) is a (Manager) tool that manages Node.js packages.

A Node.js package is a collection of useful functions (various frameworks and libraries) prepared in advance.

yarn

yarn is a package manager compatible with npm released in 2016.

I won't touch on the yarn command this time, but I'm very convinced by the following opinion. For your reference.

By the way: There is a similar CLI, Yarn, developed by Facebook. It's designed to make up for various shortcomings of npm (such as speed) and is quite popular. The npm package README often mentions both how to install with npm and yarn, and sometimes says "I recommend using yarn". However, npm has also improved, and I don't think there is much benefit to installing and using yarn. Especially for beginners, using non-standard tools is not recommended as it will increase wasteful learning.

[For beginners] Conceptual understanding of NPM and package.json (excerpt) https://qiita.com/righteous/items/e5448cb2e7e11ab7d477

package.json

package.json is a file used to manage its own package (= project itself) in Node.js-based JavaScript application development.

Running the command npm init will create package.json.

package-lock.json Briefly, it is a file that describes the result of installing a package using package.json. I will omit the explanation this time, but if you want to know more, please refer to the [Reference] link.

【reference】 What is package-lock.json?

npm init

You can usually create package.json with the touch command, but basically you can create package.json by executing the command npm init.

([Derailment] What if I don't do npm init?)

#Empty empty directory
$ ls
(No standard output)

#package with npm init.Create json (questioned but once all go through with Enter= npm init -y Same behavior as when the command is executed)
$ npm init

# package.json has been created
$ ls
package.json

The initial value of package.json is as follows.

package.json


{
  "name": "<current directory name>",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

There are various items in package.json, but data such as name, version, description, keywords, author, license are just metadata of your own package (= project itself). Yes, if you don't publish your own package (= project itself), don't worry.

If you suppress about 4 of dependencies, devDependencies, scripts, config, I think that there is no problem if you check and set as necessary.

【reference】 Structure of package.json

Relationship between npm and package.json

Published packages (libraries, frameworks, etc.) can be installed with the npm command.

Installing a package with the npm command in the directory where package.json resides will automatically update package.json.

Also, ** humans do not edit package.json directly. ** **

** Update everything via the npm command. (Important) **

node_modules node_modules is the directory where various packages installed based on package.json are installed.

As long as you have package.json, you can generate node_modules by running the npm install command.

Therefore, it is usually the directory specified in .gitignore.

npm install

This is the main subject of this article.

Run the command npm install to install the package on node_modules.

This command is npm install, but since there are various types and it is complicated, I will explain it in detail.

List of frequently used commands for the time being

** When executing with no arguments **

#Argumentless execution (package.Execute in the directory with json)
npm install

** Global installation **

#Global installation
npm install -g <package>
npm install --global <package>

** Local installation **

#Local installation
# package.When adding to json dependencies (in npm v4 and below)--save (= -S)Option required, not required on npm v5 and above as it is the default)
npm install <package>
npm install --save <package> #No need to use as it is an option included by default
npm install -S <package> #No need to use as it is an option included by default

# package.When adding to json's devDependencies--save-dev (= -D)
npm install --save-dev <package>
npm install -D <package>

** Versioned installation **

#Version specification
npm install <package>@x.y.z #When specifying the version
npm install <package>@latest #When specifying the latest version (@If you do not specify the latest version, the latest version will be installed.)

No arguments npm install

The behavior when executing the npm install command without arguments is easier to understand if you think of it asnpm install <package>with arguments.

** If you execute the npm install command with no arguments, the packages described in package.json in the current directory will be installed in node_modules (installation destination) based on the information described there. ** **

** The timing to use is "when package.json is shared and node_modules is not created" or "when package.json is updated". ** **

Also, before executing the npm install command, you need to write the package information you want to install in package.json in advance.

Then, the package information in that package.json is described by executing the command npm install <package> with arguments.

With arguments npm install <package>

It can be roughly divided into global installation and local installation. Also, even in the local installation, it can be divided into two depending on the description destination of package.json.

Overall, there are three types, one for global installation and two for local installation.

command Major classification package.Description destination of json
npm install -g <package> Global installation -
npm install <package> Local installation dependencies
npm install -D <package> Local installation devDependencies

By the way, both "global installation" and "local installation" are installed in the environment of your own PC.

Global installation

With global installation, you can execute the installed packages (commands) anywhere in your PC environment.

However, even if you install globally, if you manage multiple Node.js versions with nodebrew etc., the packages withnpm install -g <package>in each version will be managed as different ones. Please note that it will be done.

【reference】 [Npm] Confirmation of package installation destination (npm list)

** Global installation behavior **

#The cowsay command cannot be executed because it is not installed.
$ cowsay "hoge"
zsh: command not found: cowsay

#Global installation of cowsay command
$ npm install -g cowsay
$ cowsay "hoge"
 ______
< hoge >
 ------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

Local installation

Local installation allows packages (commands) to be executed if they are in the same directory as node_modules.

【reference】 How to execute a command locally installed package with npm with CLI (npm-srcipts, npx)

Local installation behavior (without the -D option)

#Install the appropriate package (cowsay)
$ npm install cowsay
+ [email protected]

#You can see that cowsay has been added to the dependencies item
$ cat package.json
{
(abridgement)
+ "dependencies": {
+   "cowsay": "^1.4.0"
+ },
(abridgement)
}

# node_Since it is installed in modules, it can be executed while passing through the path
$ ./node_modules/.bin/cowsay "hoge" 
 ______
< hoge >
 ------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

Local installation behavior (with the -D option)

#Appropriate package (typescript)-Install with D option
$ npm install -D typescript
+ [email protected]

#You can see that the typescript of the devDependencies item has been added
$ cat package.json
{
(abridgement)
  "dependencies": {
    "cowsay": "^1.4.0"
  },
+ "devDependencies": {
+   "typescript": "^4.0.3"
+ },
(abridgement)
}

# -Even with the D option, it doesn't change node_Since it is installed in modules, it can be executed while passing through the path
$ ./node_modules/.bin/tsc --version 
Version 4.0.3

Proper use of global installation and local installation

So, when installing a package, should I install it on ** Global Install ** or ** Local Install **?

Depending on the situation, ** you should avoid global installation in the dark clouds. ** **

Globally installed packages cannot be used in different environments.

For example, if you buy a new PC, you cannot use the package, and you cannot use the package on another person's PC.

At that time, if you share only the package.json created by the local installation, you can use the same package in any environment just by running npm install.

** I think it's safe to globally install only the package "I want to use that command anytime, anywhere in any directory" and install the others locally. ** **

Cases where the -D option should be added during local installation

** Generally, use npm install -D <package> for packages that are only used in the development environment, and npm install <package> for packages that aren't. ** **

You can install npm install, which does not take a package name argument, on node_modules by adding the option --production, except for the packages installed by npm install -D <package>.

By adding the --production option in this way, you can exclude packages that are only used in the development environment, so you do not have to install packages that are not referenced during production deployment.

The differences between the presence and absence of the -D option during local installation are summarized below.

Command to execute package.Description destination of json How to use each
npm install <package> dependencies Packages that are also used outside the development environment
ex) express
npm install -D <package> devDependencies Packages used only in the development environment
ex) eslint

In addition, the difference between the presence and absence of the --production option at the time of executing npm install that does not take the argument of the package name is summarized as follows.

Command to execute Installation target Timing to execute
npm install dependencies
devDependencies
Development environment
npm install --production dependenciesonly When you do not want to install a package that is used only in the development environment such as the production environment

I've written a lot, but it's case by case, so I think you should think about it when you actually do npm install --production.

【reference】 [Package.json] Consider how to use dependencies and devDependencies properly

Summary

The timing of using each npm install command is summarized below.

command Timing to use
npm install New or updated package.node based on json_When creating modules
npm install -g <package> When installing globally (=When you want to be able to use the command in any directory)
npm install <package> package.I want to install locally in json (=When adding a package (which you want to use only in that directory) (a package that is also used in the production environment)
npm install -D <package> package.I want to install locally in json (=When adding a package (which you want to be able to use only in that directory) (a package that is used only in the development environment)

finally

How was that? Now you can use the following four npm install commands properly.


** Here are the URLs of articles about npm that didn't fit in here ↓ **

A note about Node.js version control (nodebrew, nodenv) https://qiita.com/sugurutakahashi12345/items/20803f553b5716c13902

[Npm] Confirmation of package installation destination (npm list) https://qiita.com/sugurutakahashi12345/items/8820b09db0dc1507f563

A note about semantic versioning https://qiita.com/sugurutakahashi12345/items/68e9dfb11e84d20acc6d

About tilde ^ and caret ~ described in package.json https://qiita.com/sugurutakahashi12345/items/0876ce674587515c66ba

What is package-lock.json? https://qiita.com/sugurutakahashi12345/items/1f6bb7a372b8263500e5

What if I don't npm init? https://qiita.com/sugurutakahashi12345/items/1049a33b86225f6345fe

How to execute commands with CLI for packages installed locally with npm (npm-srcipts, npx) https://qiita.com/sugurutakahashi12345/items/b814a09b65d8852226ad

When the package name and command are different in npx (npx -p <package> -c" <commond> ") https://qiita.com/sugurutakahashi12345/items/329e0cdbaf337edb81d3

npm-scripts pre, post prefix https://qiita.com/sugurutakahashi12345/items/91a133abacfc38b3d7a7

Sequential / parallel execution of npm-scripts (npm-run-all) https://qiita.com/sugurutakahashi12345/items/2a17a3cdfbc4a7e5e4eb

How to upgrade the package described in package.json [npm-check-updates, outdated] https://qiita.com/sugurutakahashi12345/items/df736ddaf65c244e1b4f

How to use config of package.json https://qiita.com/sugurutakahashi12345/items/357fc6c2ae04f48b2076

Recommended Posts

I want to graduate from npm install properly [2020]
I want to install PHP 7.2 on Ubuntu 20.04.
Run R from Java I want to run rJava
I want to play with Firestore from Rails
I want to write quickly from java to sqlite
[Java] I want to calculate the difference from the date
I want to redirect sound from Ubuntu with xrdp
I want to connect to Heroku MySQL from a client
I want to convert characters ...
Swift: I want to chain arrays
I want to use FormObject well
I want to convert InputStream to String
I want to docker-compose up Next.js!
I want to operate cron with GUI, so I will install Dkron
I want to add devise in Rails, but I can't bundle install
[Android] I want to get the listener from the button in ListView
I want to write a nice build.gradle
I want to eliminate duplicate error messages
I want to make an ios.android app
I want to display background-ground-image on heroku.
I want to use DBViewer with Eclipse 2018-12! !!
I want to RSpec even at Jest!
I want to write a unit test!
I want to mess with Permission of Windows directory from WSL (ubuntu)
I want to stop Java updates altogether
I tried to build Ruby 3.0.0 from source
I want to use @Autowired in Servlet
I want to target static fields to @Autowired
I want to do team development remotely
I want to find out what character the character string appears from the left
I want to get only the time from Time type data ...! [Strftime] * Additional notes
I want to test Action Cable with RSpec test
I want to sort by tab delimited by ruby
I want to output the day of the week
[Swift] I want to draw grid lines (squares)
[Rails] I tried to raise the Rails version from 5.0 to 5.2
I want to send an email in Java.
I want to use arrow notation in Ruby
[Ruby] I want to do a method jump!
I want to use java8 forEach with index
I want to var_dump the contents of the intent
I want to pass APP_HOME to logback in Gradle
I want to simply write a repeating string
I want to design a structured exception handling
rsync4j --I want to touch rsync in Java.
[Xcode] I want to manage images in folders
I want to be eventually even in kotlin
I want to truncate after the decimal point
I want to reduce simple mistakes. To command yourself.
I want to perform aggregation processing with spring-batch
[Rails] I want to load CSS with webpacker
I want to delete files managed by Git
I want to get the value in Ruby
I want to output the character number from the left where an arbitrary character string appears.
I updated Node.js with nodebrew and scripted the routine to re-install npm install -g
I want to reduce the number of unnecessary queries. From considering counter_cache to introducing counter_culture.
I want to use Combine in UIKit as well.
I want to use Clojure's convenient functions in Kotlin
I want to call a method of another class
I want to do something like "cls" in Java
I want to use NetBeans on Mac → I can use it!