I. What is Node.js and npm?¶
Before starting with npm, let’s briefly understand its “identity”:
- Node.js: A JavaScript runtime environment built on Chrome’s V8 engine, enabling JavaScript to run server-side outside of browsers. It allows frontend developers to write backend code, enabling full-stack development.
- npm: Short for Node Package Manager, npm is Node.js’s default package management tool, acting like an “app store” for Node.js. With npm, you can quickly download, install, and manage pre-written JavaScript code packages (e.g., frameworks, utility libraries), avoiding redundant development work (“reinventing the wheel”).
II. Installing Node.js and npm¶
To use npm, you first need to install Node.js (npm is bundled with Node.js). Here are installation methods for different operating systems:
1. Windows¶
- Download from official website: Visit the Node.js official site, click “Download” to get the version matching your system (LTS stable version is recommended).
- During installation, check “Add to PATH” (auto-configures environment variables), then follow the prompts.
- Verification: Open Command Prompt (CMD) or PowerShell and run:
node -v # Should show version (e.g., v18.16.0)
npm -v # Should show npm version
2. macOS¶
- Method 1 (Recommended): Use Homebrew:
First, install Homebrew (if not already installed):
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Then run:
brew install node
- Method 2: Download the installer from the official site (similar to Windows steps).
- Verification: Open Terminal and run
node -vandnpm -v.
3. Linux (Ubuntu example)¶
- Open Terminal and execute:
sudo apt update
sudo apt install nodejs npm
- Verification: Same as above.
III. npm Core Function: Initializing a Project¶
Before using npm to manage dependencies, initialize a project to generate a package.json file (project configuration that records project info and dependencies).
Steps:
1. Create a new folder (e.g., my-project) and open the terminal in that directory.
2. Run npm init and follow prompts to fill in project details (or use npm init -y for a quick default configuration).
3. The generated package.json will include basic project info:
{
"name": "my-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
The scripts field is critical; use it to define project commands (e.g., npm start).
IV. Installing Dependencies: npm install¶
npm’s most common feature is installing third-party packages. Basic syntax:
npm install <package-name>
1. Local vs. Global Installation¶
- Local Installation (default): Packages are installed in the project’s
node_modulesfolder and only available to the current project.
Example: Install the web frameworkexpress(production dependency):
npm install express --save
(--save automatically adds the dependency to package.json under dependencies).
- Global Installation (
-gflag): Packages are installed to a system-wide directory and accessible across all projects.
Example: Install the code formatting toolprettier(global utility):
npm install -g prettier
Verify with prettier --version in the terminal.
2. Production vs. Development Dependencies¶
- Production Dependencies (
dependencies): Required for the project to run (e.g.,react,vue,express).
Install with--save(or-S):
npm install react --save
- Development Dependencies (
devDependencies): Only needed during development (e.g., code linters likeeslint, build tools likewebpack).
Install with--save-dev(or-D):
npm install eslint --save-dev
Note: Dependencies can be omitted from the
--saveflag ifpackage.jsonis properly configured; npm will auto-assign types.
V. Managing Dependencies: View, Update, Uninstall¶
1. View Installed Dependencies¶
- List all dependencies:
npm list
(Displays the dependency tree under node_modules).
- List production dependencies only:
npm list --production
2. Update Dependencies¶
- Update a specific package:
npm update <package-name>
- Update all dependencies:
npm update
3. Uninstall Dependencies¶
- Uninstall a production dependency:
npm uninstall <package-name>
(Automatically removes it from package.json and node_modules).
- Uninstall a development dependency:
npm uninstall <package-name> --save-dev
4. Clean Up Unused Dependencies¶
Remove dependencies not declared in package.json:
npm prune
VI. Quick Reference for Common npm Commands¶
| Command | Purpose |
|---|---|
npm init |
Initialize project and generate package.json |
npm install <package> |
Install package locally (default: production dependency) |
npm install -g <package> |
Install package globally |
npm install -S <package> |
Install production dependency |
npm install -D <package> |
Install development dependency |
npm uninstall <package> |
Uninstall package |
npm update <package> |
Update package to latest compatible version |
npm list |
List all installed dependencies |
npm start |
Run the start script in package.json |
npm run <script> |
Run a custom script (e.g., npm run build) |
VII. Practical Tips: Speeding Up Domestic Access¶
Due to npm’s overseas server location, domestic users may experience slow downloads. Use these methods:
1. Use Taobao Mirror (Recommended)¶
- Temporarily use Taobao mirror for installation:
npm install <package-name> --registry=https://registry.npm.taobao.org
- Permanently set Taobao mirror:
npm config set registry https://registry.npm.taobao.org
- Verify:
npm config get registry # Should return Taobao's URL
2. Use cnpm (Taobao’s Official Tool)¶
- Install cnpm:
npm install -g cnpm --registry=https://registry.npm.taobao.org
- Use cnpm as a drop-in replacement for npm:
cnpm install <package-name>
VIII. Important Notes¶
- Never commit
node_modulesto Git:
node_modulesis large and redundant. Add to.gitignore:
node_modules/
package-lock.json
-
Version Number Rules:
Use^(compatible minor updates) or~(only patch updates) inpackage.json:
-^1.2.3: Allows updates to1.3.xor1.4.x.
-~1.2.3: Only allows updates to1.2.x. -
Avoid Overusing Global Installs:
Global packages are terminal-only. Project dependencies should be local to prevent version conflicts.
Conclusion¶
npm is a core tool for Node.js development, significantly improving efficiency. Key concepts include initializing projects, managing dependencies (production/development), and understanding package.json. With the steps and examples above, you can quickly master npm. For advanced usage (e.g., script configuration, version locking), explore further in project practice.
Now, open your terminal and try creating a project and installing your first dependency! 🚀