Installing packages for different purposes

There are two ways of installing npm packages: globally or locally:

  • If you plan to use the package from the command line, install it globally; for example, npm install prettier -g would install the prettier command so you can use it anywhere. (We'll see more of prettier in the Formatting your source code with Prettier section.) You may need to run the command as an administrator, or with sudo.
  • Otherwise, if you just need the package for your project, install it locally. 

Installing packages locally can also be done in more than one way:

  • If you need the package for your own project, then you install it as a production package with npm install lodash --save
  • Instead, if you need the package in order to build your project, but not as a part of the final, produced code, install it as a development package with npm install eslint --save-dev
There are many shorthand versions for commands and options, such as just i for install, or -D for --save-dev, but I am more comfortable spelling everything out. If you want to learn more about this, just try npm --help.

After running these two latter commands, if you inspect package.json, you'll notice that some lines were added:

~/sample> cat package.json  
{
"name": "simpleproject",
"version": "1.0.0",
"description": "A simple project to show package.json creation",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "Federico Kereki",
"license": "ISC",
"dependencies": {
"lodash": "^4.17.5"
},
"devDependencies": {
"prettier": "^1.11.1"
}
}

The dependencies and devDependencies entries refer to the production and development packages you require. If you are writing your software, and you decide you need a new package, there are two ways of doing this:

  • Add an entry to package.json, in the proper place, and then do npm install to get it
  • Alternatively, use npm install with either --save or --save-dev, and package.json will be updated by npm
To remove a dependency, use npm uninstall instead. You must include --save or --save-dev in order to also remove the reference from package.json.

If you need specific versions, you will have to learn about semantic versioning. Version rules may become complex, and we'll just see the main ones; check https://docs.npmjs.com/files/package.json#dependencies and https://github.com/npm/node-semver#versions for a complete description:

4.5.6
Version 4.5.6, and none other
^4.0.0
Latest compatible version 4.x.x
^4.2.0
Latest compatible version 4.2.x
>5.6.7
A version greater than 5.6.7
~8.7.6
A version approximately equivalent to 8.7.6; should be 8.7.x
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset