Skip to content

Latest commit

 

History

History
136 lines (99 loc) · 4.16 KB

npm-fundamentals.md

File metadata and controls

136 lines (99 loc) · 4.16 KB

NPM Fundamentals

Introduction to the Node Package Manager

  • Platform for creating reusable code packages (aka modules)
    • Metadata (package.json)
    • Tooling (npm) installed with Node.js
    • NPM Website
  • Version management
  • It is huge!
    • Over 500k packages
    • Over 10 billion downloads per month

Installing a Package

  • Open a shell in an empty folder
  • Search for package Chalk: npm search chalk
  • Run: npm install chalk
  • Create app.js using the Chalk package
const chalk = require('chalk');
console.log(chalk.red.bgBlue('Hello world!'));
  • Run program: node app.js

node_modules Folder

  • Stores all locally installed packages
    • ...and their dependencies, and the dependencies of the dependencies...
  • Can contain large number of files
  • Problems
    • How to find out which packages a program needs?
    • How to find out if new versions of packages are available?
    • How to reinstall necessary packages on a target machine?
  • Solution: package.json

Local Command Line Interfaces

NPM local install

More about FIGlet...

Global Command Line Interfaces

NPM global install

Creating package.json

  • Open a shell in an empty folder
  • Run: npm init
  • Answer questions (hit enter to accept default)
  • Run: npm install chalk
  • Take a look at the generated package.json file, especially note dependencies object
{
  "name": "npmdemo",
  "version": "1.0.0",
  "description": "...",
  ...
  "dependencies": {
    "chalk": "^2.0.1"
  }
}

Version Numbers in package.json

  • 3.5.0 means: Take currently latest version of the package
    • It does not mean: Take version 3.5.0
  • ^3.5.0 means: Take most recent major version (i.e. 3.x.x)
  • ~3.5.0 means: Take most recent minor version (i.e. 3.5.x)
  • Related: Semantic Versioning standard
  • Install a specific version of a package with e.g. npm install chalk@^1.0.0

Dependency Tree

Chalk dependencies

  • Recursive tree of dependencies
  • Cached in package-lock.json
    • Exercise: Open package-lock.json and view dependencies
  • Visualize dependency tree in 2d or 3d

package.json Content

  • Package metadata (e.g. author, description, etc.)
  • Version number
  • Dependencies
    • Necessary at runtime (dependencies)
    • Necessary at compile time (devDependencies, --save-dev option, will later be important for TypeScript)
  • Collection of scripts (npm scripts)
    • Run at certain events (e.g. after install)
    • Run with npm run script-name
    • Note that node_modules/.bin is automatically added to the path
  • Exercise: Inspect package.json from jQuery
  • Read more details about package.json

package.json Content

Path in NPM scripts

Further Readings and Exercises