npm in a nutshell

npm

npm is a JavaScript packagemanager providing both back-end and front-end packages.

npm makes it easy for JavaScript developers to share and reuse code, and it makes it easy to update the code that you're sharing.

intsallation

npm comes with node.js.

You might want to update it from time to time with npm install npm -g

package.json

A package.json file affords you a lot of great things:

  • It serves as documentation for what packages your project depends on.
  • It allows you to specify the versions of a package that your project can use using semantic versioning rules.
  • Makes your build reproducible which means that its way easier to share with other developers.

Minimum

As a bare minimum, a package.json must have:

  • "name"
    • all lowercase
    • one word
    • no spaces, dashes and underscores allowed
  • "version"
    • in the form of x.x.x

For example:

{ "name": "my-awesome-package", "version": "1.0.0" }

npm init will initiate a command line questionnaire that will conclude with the creation of a package.json in the directory you initiated the command.

packages

npm install installs all the packages listed in the package.json.

To add packages your project depends on, you need to put them the packages in your package.json file. There are 2 types of packages you can list:

  • dependencies these packages are required by your application in production
  • devDependencies these packages are only needed for development and testing

Add dependencies to your package.json from the command line, flagging the npm install command with either --save or --save-dev, depending on how you'd like to use that dependency.

To add a package dependency:
npm install <package_name> --save

To add a package devDependency:
npm install <package_name> --save-dev

If you want to the --save flag as default use npm config set save=true

example

{ // the name of this package... "name": "my_package", // always x.x.x "version": "1.0.0", "description": "this is an aesome package", // by default creates a empty test script "scripts": { "test": "echo \"Error: no test specified\" && exit 1", // starting the main script with `npm start` "start": "node index.js" }, "keywords": [], "author": "someone", "license": "UNLICENSED", "repository": { "type": "git", "url": "https://github.com/ashleygwilliams/my_package.git" }, "bugs": { "url": "https://github.com/ashleygwilliams/my_package/issues" }, "homepage": "https://github.com/ashleygwilliams/my_package", "dependencies": { "my_dep": "^1.0.0" }, "devDependencies" : { "my_test_framework": "^3.1.0" } }

Reference

No known

History Nov 22, 2017