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/package2npm link
Linking is useful for testing local packages without publishing them to npm.
Unlinking a Local Package
ruby snippet
1cd ~/path/to/package2npm 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 version3npx <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 install2# or shorthand3npm i
Installing a Specific Package
ruby snippet
1npm install <package-name>2# Install as a dev dependency3npm install <package-name> --save-dev
Updating Dependencies
ruby snippet
1npm update2# Update a specific package3npm update <package-name>
Version Management
Viewing Package Versions
ruby snippet
1npm version2# View a specific package version3npm view <package-name> version
Incrementing Package Version
ruby snippet
1npm version patch2npm version minor3npm 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 init2# Use defaults3npm init -y
Auditing Dependencies for Security Vulnerabilities
ruby snippet
1npm audit2# Automatically fix issues3npm audit fix