Essential npm Commands

Essential npm Commands for Local Development

This guide covers frequently used npm commands for local development, package management, and CLI tool creation.

Package Linking and Management

Linking a Local Package

Terminal
1cd ~/path/to/package
2npm link
Linking is useful for testing local packages without publishing them to npm.

Unlinking a Local Package

ruby snippet
1cd ~/path/to/package
2npm unlink

Removing a Package Globally

ruby snippet
1npm rm --global <package-name>
Be careful when removing global packages, as it might affect other projects.

Checking Installed Packages

ruby snippet
1npm list --global
Use npm list without --global to check local project dependencies.

Package Execution and Cache Management

Clearing the npx Cache

ruby snippet
1rm -rf ~/.npm/_npx

Running a Package without Global Installation

ruby snippet
1npx <package-name>
2# Use @latest to ensure you're using the most recent version
3npx <package-name>@latest
npx is great for running one-off commands or trying out packages without installing them globally.

CLI Development with Node.js and TypeScript

Example package.json Configuration

ruby snippet
1{
2 "scripts": {
3 "dev": "tsc -w && npm run link",
4 "start": "node dist/index.js",
5 "build": "esbuild src/index.ts --bundle --platform=node --target=node18 --outfile=dist/index.js",
6 "up": "npm run build && npm publish --access public && npm run unlink",
7 "link": "npm unlink your-cli && npm i -g && chmod +x ./dist/index.js && npm link your-cli",
8 "unlink": "npm rm -g your-cli && npm unlink your-cli"
9 },
10 "bin": {
11 "your-cli": "./dist/index.js"
12 }
13}
This configuration is tailored for building a CLI tool with Node.js, TypeScript, and esbuild.

Dependency Management

Installing Dependencies

ruby snippet
1npm install
2# or shorthand
3npm i

Installing a Specific Package

ruby snippet
1npm install <package-name>
2# Install as a dev dependency
3npm install <package-name> --save-dev

Updating Dependencies

ruby snippet
1npm update
2# Update a specific package
3npm update <package-name>

Version Management

Viewing Package Versions

ruby snippet
1npm version
2# View a specific package version
3npm view <package-name> version

Incrementing Package Version

ruby snippet
1npm version patch
2npm version minor
3npm version major
Use semantic versioning to manage your package versions effectively.

Publishing Packages

Publishing a Package

ruby snippet
1npm publish
Ensure your package name is unique and you have the necessary permissions before publishing.

Publishing a Scoped Package

ruby snippet
1npm publish --access public

Script Execution

Running npm Scripts

ruby snippet
1npm run <script-name>
Custom scripts defined in package.json can be run using npm run.

Miscellaneous

Initializing a new npm Project

ruby snippet
1npm init
2# Use defaults
3npm init -y

Auditing Dependencies for Security Vulnerabilities

ruby snippet
1npm audit
2# Automatically fix issues
3npm audit fix