npm package manager π€
npm (7.4k β) is the most well-known package manager for Node.js, as it comes bundled with the official Node.js installer.
$ npm install -g npm
$ npm -v
- See the documentation here.
- Use npmjs to find packages (Registry API).
npm uses a file called package.json
to know which packages to import into your project. As versions are usually based on a rule, the exact version of the package can be found in package-lock.json
.
New Project
Create an empty project with an empty package.json
.
$ npm init
All installed packages are stored in the folder node_modules
. Add it to your .gitignore
, because it's heavy and useless. β οΈ
Instead, commit package-lock.json
. Someone else will be able to generate back the same node_modules
with a command.
β‘οΈ Commit package.json
too, so that devs can add packages...
Existing Project
Install packages from an existing project (package-lock.json
).
$ npm ci
$ npm ci --production # only non-dev packages
Update dependencies
Add packages in package.json/dependencies
and install them.
# add in package.json/dependencies + install it
$ npm i express # π€
$ npm install express # β
$ npm install xxx -D # install as dev package
$ npm install xxx --save-dev # same
# generate package-lock.json from package.json
$ npm install # all packages
$ npm install --production # only non-dev packages
# Update package-lock.json
$ npm update
Define which versions are allowed
Either when installing or by editing the package.json
, you can select which version of a library you want to use.
# when used with "i", use "@" followed by the "version"
$ npm i express@latest
- ^1.2.3: same major version (1), can change (2.3)
- ~1.2.3: same major+minor version (1.2), can change (3)
- >=version: version greater or equals (see also
>,<,<=
) - =version: this exact version
- a-b: a range of versions
- a||b: either a or b
- latest: use the latest
β‘οΈ If you see an example with require('xxx')
, then it's rather safe to assume that you can use npm i xxx
.
Add scripts
Usually, we store the commands to run/test... a project in package.json/scripts
. To run "start" below, use npm start
.
{
"scripts": {
// "npm start" will run "node index.js"
"start": "node index.js"
}
}
π» To-do π»
Stuff that I found, but never read/used yet.
- npx
- .npmignore
--save
/-S
(before ~2017, npm install didn't add the dependency in package.json)-g
(+not recommended)
npm config
npm config set xxx yyy
npm --arch=xxx --target_arch=xxx
npm outdated
npm prune
npm cache add
+npm install --no-registry