阿里云主机折上折
  • 微信号
Current Site:Index > Basic concepts of packages and NPM

Basic concepts of packages and NPM

Author:Chuan Chen 阅读数:37231人阅读 分类: Node.js

Basic Concepts of Packages and NPM

Packages and NPM are indispensable parts of the Node.js development ecosystem. Packages are collections of code, while NPM is the tool used to manage these packages. Understanding how they work can improve development efficiency.

What is a Package?

A package is a reusable code module in Node.js, typically consisting of one or more JavaScript files. Each package has a package.json file that describes its metadata. For example:

{
  "name": "my-package",
  "version": "1.0.0",
  "description": "A sample package",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Packages can range in scale from simple utility functions to complex frameworks. For instance, lodash provides utility functions, while express is a web framework.

Detailed Explanation of package.json

This file is the core of a package and contains important configurations:

{
  "name": "my-app",
  "version": "1.0.0",
  "dependencies": {
    "lodash": "^4.17.21"
  },
  "devDependencies": {
    "jest": "^27.0.6"
  },
  "scripts": {
    "start": "node index.js",
    "test": "jest"
  }
}
  • dependencies: Production environment dependencies
  • devDependencies: Development environment dependencies
  • scripts: Runnable commands

Symbols before version numbers have specific meanings:

  • ^4.17.21: Allows updates to minor and patch versions
  • ~4.17.21: Only allows patch version updates
  • 4.17.21: Exact version

How NPM Works

NPM is Node.js's package manager, with primary functions including:

  1. Installing Dependencies:
npm install lodash
  1. Global Installation:
npm install -g nodemon
  1. Development Dependencies:
npm install jest --save-dev

The installation process generates a node_modules directory and a package-lock.json file, the latter of which locks dependency versions to ensure consistency.

Creating and Publishing Packages

Creating a new package:

mkdir my-package
cd my-package
npm init -y

After writing the functional code, publish it with:

npm login
npm publish

Updating the version number:

npm version patch
npm version minor
npm version major

Common NPM Commands

  • Check for outdated packages:
npm outdated
  • Update packages:
npm update
  • Uninstall a package:
npm uninstall lodash
  • View installed packages:
npm list
  • Run scripts:
npm run test

Package Scopes

NPM supports scoped packages for organizing related packages:

{
  "name": "@myorg/mypackage",
  "version": "1.0.0"
}

When installing, specify the scope:

npm install @myorg/mypackage

Dependency Management Strategies

The structure of node_modules has evolved:

  1. Nested Structure: Early versions, with dependencies nested layer by layer
  2. Flat Structure: Current default, reducing duplication
  3. pnpm: An alternative using hard links

View the dependency tree with:

npm ls --depth=1

Advanced Usage of NPM Scripts

Scripts can be combined:

{
  "scripts": {
    "build": "webpack",
    "deploy": "npm run build && rsync -avz ./dist/ user@example.com:/var/www/"
  }
}

Passing environment variables:

{
  "scripts": {
    "start": "NODE_ENV=production node server.js"
  }
}

NPM Configuration

View configuration:

npm config list

Set a mirror source:

npm config set registry https://registry.npmmirror.com

Configure the global installation path:

npm config set prefix '~/.npm-global'

Private Package Management

Common enterprise solutions for private repositories:

  1. NPM Private Repository
  2. Verdaccio (open-source solution)
  3. GitHub Packages

Installing private packages requires authentication:

npm login --registry=https://your.private.registry
npm install @private/package

Package Version Management Practices

Semantic Versioning (SemVer) specifications:

  • MAJOR: Incompatible API changes
  • MINOR: Backward-compatible feature additions
  • PATCH: Backward-compatible bug fixes

Pre-release versions:

npm version 1.0.0-beta.1

Package Management in Modern Frontend Projects

Common tools for large projects:

  1. Yarn: Developed by Facebook as an alternative
  2. pnpm: A disk-space-saving solution
  3. Lerna: Multi-package repository management

Monorepo configuration example:

{
  "private": true,
  "workspaces": [
    "packages/*"
  ]
}

Security Considerations for Packages

Security audit:

npm audit

Fixing vulnerabilities:

npm audit fix

Automatically updating dependencies:

npm install -g npm-check-updates
ncu -u
npm install

Package Development Tips

When developing local packages, use npm link:

cd /path/to/my-package
npm link
cd /path/to/my-app
npm link my-package

Creating executable commands:

{
  "bin": {
    "my-cli": "./bin/cli.js"
  }
}

cli.js must start with a shebang:

#!/usr/bin/env node
console.log('Hello from CLI!');

Package Testing and Publishing

Continuous integration configuration example (.travis.yml):

language: node_js
node_js:
  - "14"
script:
  - npm test
deploy:
  provider: npm
  email: user@example.com
  api_key: $NPM_TOKEN
  on:
    tags: true

Running tests automatically before publishing:

{
  "scripts": {
    "prepublishOnly": "npm test"
  }
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.