Nội dung

Dai Phan

Dai Phan

Full-Stack Developer

Full-stack developer passionate about modern web technologies, best practices, and sharing knowledge with the community.

Skills & Expertise

JavaScript TypeScript React Node.js DevOps
150+
Articles
50k+
Readers
4.9
Rating

NPM Package Management Best Practices

Hướng dẫn chi tiết về quản lý package với NPM, từ cơ bản đến nâng cao

NPM Package Management Best Practices

NPM (Node Package Manager) là công cụ quản lý package mặc định cho Node.js, giúp chúng ta dễ dàng cài đặt, chia sẻ và quản lý các thư viện JavaScript.

Cài đặt và Khởi tạo

Khởi tạo project mới

npm init
npm init -y  # Tự động chấp nhận tất cả các giá trị mặc định

Cài đặt package

# Cài đặt cho production dependencies
npm install express
npm i express

# Cài đặt cho development dependencies
npm install --save-dev jest
npm install -D jest

# Cài đặt global
npm install -g typescript

Quản lý phiên bản

Semantic Versioning (SemVer)

  • Major breaking changes: 2.0.0
  • Minor new features: 1.2.0
  • Patch fixes: 1.2.3

Kiểm tra các package cần cập nhật

npm outdated

Cập nhật package

# Cập nhật các minor và patch versions
npm update

# Cập nhật đến phiên bản mới nhất
npm install package@latest

# Cập nhật global packages
npm update -g

Scripts trong package.json

{
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js",
    "test": "jest",
    "build": "webpack --mode production",
    "lint": "eslint . --ext .js"
  }
}

Security và Security Audit

# Kiểm tra lỗ hổng bảo mật
npm audit

# Sửa các lỗ hổng automatically
npm audit fix

# Kiểm tra severity levels
npm audit --audit-level=moderate

Best Practices

1. Sử dụng exact versions cho production

npm install --save-exact react

2. Lock file management

  • Luôn commit package-lock.json vào version control
  • Không edit thủ công package-lock.json

3. Dependencies cleanup

# Xóa các unused dependencies
npm prune

# Kiểm tra các dependencies không được sử dụng
npm ls --depth=0

4. Cấu hình .npmrc

# .npmrc
prefix=~/.npm-global
cache=/path/to/cache
@mycompany:registry=https://npm.mycompany.com/

Advanced Commands

Unpublishing packages

# Unpublish version cụ thể
npm unpublish package@1.0.0

# Unpublish toàn bộ package (chỉ trong 24h)
npm unpublish package

Creating scoped packages

npm init --scope=@mycompany
npm publish --access public

Troubleshooting

Xóa node_modules và reinstall

rm -rf node_modules package-lock.json
npm install

Clear npm cache

npm cache clean --force

Kiểm tra package information

npm view express
npm view express versions

Kết luận

Việc quản lý package hiệu quả là kỹ năng quan trọng trong phát triển Node.js. Bằng cách tuân thủ các best practices trên, bạn có thể duy trì project một cách chuyên nghiệp và an toàn.