04-npm 与 Bun 快速入门实战指南

引言

作为 JavaScript/TypeScript 开发者,包管理器 是你每天都要打交道的工具。本文将帮助你快速掌握 npmBun 的核心用法,让你能够立即投入实际开发。

💡 阅读提示:本文采用对照学习法,npm 和 Bun 命令并排展示,方便你理解和记忆。


第一部分:核心概念

什么是包管理器?

包管理器帮你解决三个核心问题:

复制代码
┌─────────────────────────────────────────────────────────┐
│                    包管理器的作用                         │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  1. 📦 安装第三方代码库(依赖)                           │
│     → 不用自己造轮子                                     │
│                                                         │
│  2. 📋 管理项目依赖版本                                  │
│     → 确保团队成员使用相同版本                            │
│                                                         │
│  3. 🚀 运行项目脚本                                      │
│     → 统一的命令入口                                     │
│                                                         │
└─────────────────────────────────────────────────────────┘

核心文件说明

|---------------------|------------------|--------------------|
| 文件 | 作用 | 是否提交到 Git |
| package.json | 项目配置文件,记录依赖列表 | ✅ 是 |
| package-lock.json | npm 的依赖锁定文件 | ✅ 是 |
| bun.lockb | Bun 的依赖锁定文件(二进制) | ✅ 是 |
| node_modules/ | 依赖安装目录 | ❌ 否(加入 .gitignore) |


第二部分:项目初始化

创建新项目

复制代码
# npm
npm init              # 交互式创建
npm init -y           # 使用默认配置快速创建

# Bun
bun init              # 交互式创建
bun init -y           # 使用默认配置快速创建

生成的 package.json 结构

复制代码
{
  "name": "my-project",
  "version": "1.0.0",
  "description": "我的项目",
  "main": "index. js",
  "scripts": {
    "start": "node index. js",
    "dev": "node --watch index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    // 生产环境依赖
  },
  "devDependencies": {
    // 开发环境依赖
  }
}

第三部分:依赖管理(最常用)

📥 安装依赖

复制代码
# ============ 安装项目所有依赖 ============
npm install           # 或 npm i
bun install           # 或 bun i(速度快 10-20 倍)

# ============ 安装生产依赖 ============
npm install lodash
bun add lodash

# ============ 安装开发依赖 ============
npm install typescript --save-dev    # 或 -D
bun add typescript --dev             # 或 -d

# ============ 安装全局工具 ============
npm install -g typescript
bun add -g typescript

# ============ 安装指定版本 ============
npm install lodash@4.17.21
bun add lodash@4.17.21

# ============ 安装多个包 ============
npm install express cors helmet
bun add express cors helmet

📤 卸载依赖

复制代码
# npm
npm uninstall lodash
npm uninstall lodash --save-dev   # 卸载开发依赖
npm uninstall -g typescript       # 卸载全局包

# Bun
bun remove lodash
bun remove lodash --dev
bun remove -g typescript

🔄 更新依赖

复制代码
# 查看可更新的包
npm outdated
bun outdated

# 更新指定包
npm update lodash
bun update lodash

# 更新所有包
npm update
bun update

命令速查表

|--------|------------------------|--------------------|
| 操作 | npm | Bun |
| 安装所有依赖 | npm install | bun install |
| 添加生产依赖 | npm install <pkg> | bun add <pkg> |
| 添加开发依赖 | npm install <pkg> -D | bun add <pkg> -d |
| 全局安装 | npm install -g <pkg> | bun add -g <pkg> |
| 卸载依赖 | npm uninstall <pkg> | bun remove <pkg> |
| 更新依赖 | npm update | bun update |
| 查看过期依赖 | npm outdated | bun outdated |


第四部分:运行脚本(每天都用)

配置 scripts

package.json 中定义脚本:

复制代码
{
  "scripts": {
    "start": "node dist/index.js",
    "dev": "node --watch src/index.js",
    "build": "tsc",
    "test": "jest",
    "lint": "eslint src/",
    "format": "prettier --write src/"
  }
}

运行脚本

复制代码
# npm(需要加 run,除了 start/test)
npm run dev
npm run build
npm start          # start 可以省略 run
npm test           # test 可以省略 run

# Bun(更简洁,都可以省略 run)
bun run dev
bun dev            # 可以省略 run
bun build
bun start
bun test

直接运行文件

复制代码
# npm/Node.js
node index.js                    # 运行 JS
node --experimental-strip-types index.ts  # 运行 TS(Node 22+)

# Bun(原生支持 TypeScript)
bun index.js
bun index.ts       # 直接运行,无需配置!
bun index.jsx      # 支持 JSX
bun index.tsx      # 支持 TSX

第五部分:实战项目演练

项目一:创建一个 Express API 服务

复制代码
# 1. 创建项目
mkdir my-api && cd my-api
bun init -y

# 2. 安装依赖
bun add express cors
bun add -d typescript @types/express @types/cors @types/node

# 3.  初始化 TypeScript
bunx tsc --init

创建 src/index. ts

复制代码
import express from 'express';
import cors from 'cors';

const app = express();
const PORT = 3000;

// 中间件
app. use(cors());
app.use(express.json());

// 路由
app.get('/', (req, res) => {
  res.json({ message: 'Hello World!' });
});

app.get('/api/users', (req, res) => {
  res.json([
    { id: 1, name: '张三' },
    { id: 2, name: '李四' },
  ]);
});

// 启动服务
app.listen(PORT, () => {
  console.log(`🚀 服务器运行在 http://localhost:${PORT}`);
});

配置 package. json

复制代码
{
  "scripts": {
    "dev": "bun --watch src/index.ts",
    "start": "bun src/index. ts"
  }
}

# 4. 启动开发服务器(支持热重载)
bun dev

项目二:使用 Bun 原生 API(更高性能)

创建 server.ts

复制代码
// 使用 Bun 原生 HTTP 服务器(性能更高)
const server = Bun.serve({
  port: 3000,
  
  async fetch(req) {
    const url = new URL(req.url);
    
    // 路由处理
    if (url.pathname === '/') {
      return Response.json({ message: 'Hello Bun!' });
    }
    
    if (url. pathname === '/api/users') {
      return Response.json([
        { id: 1, name: '张三' },
        { id: 2, name: '李四' },
      ]);
    }
    
    // POST 请求示例
    if (url.pathname === '/api/echo' && req.method === 'POST') {
      const body = await req.json();
      return Response. json({ received: body });
    }
    
    // 404
    return new Response('Not Found', { status: 404 });
  },
});

console.log(`🚀 Bun 服务器运行在 http://localhost:${server.port}`);

bun --watch server.ts

项目三:文件操作对比

复制代码
// ============ Node.js 方式 ============
import { readFileSync, writeFileSync } from 'fs';
import { readFile, writeFile } from 'fs/promises';

// 同步读取
const content = readFileSync('data.txt', 'utf-8');

// 异步读取
const asyncContent = await readFile('data.txt', 'utf-8');

// 写入文件
writeFileSync('output.txt', 'Hello World');


// ============ Bun 方式(更简洁) ============

// 读取文件
const content = await Bun.file('data.txt').text();

// 读取为 JSON
const jsonData = await Bun.file('config.json').json();

// 读取为二进制
const buffer = await Bun.file('image.png').arrayBuffer();

// 写入文件
await Bun. write('output.txt', 'Hello World');

// 写入 JSON
await Bun.write('data.json', JSON.stringify({ name: '张三' }));

第六部分:npx 与 bunx

npxbunx 用于执行包中的命令,无需全局安装。

复制代码
# 创建 React 项目
npx create-react-app my-app
bunx create-react-app my-app      # 更快

# 创建 Next.js 项目
npx create-next-app@latest
bunx create-next-app@latest

# 创建 Vite 项目
npx create-vite@latest
bunx create-vite@latest

# 运行 TypeScript 编译
npx tsc
bunx tsc

# 格式化代码
npx prettier --write . 
bunx prettier --write . 

# 检查包的大小
npx bundlephobia lodash

第七部分:依赖版本管理

版本号规则(语义化版本)

复制代码
版本格式:主版本.次版本.补丁版本
示例:    1.2.3

主版本(Major):不兼容的 API 修改
次版本(Minor):向下兼容的功能新增
补丁版本(Patch):向下兼容的问题修复

package.json 中的版本符号

复制代码
{
  "dependencies": {
    "express": "4.18.2",     // 精确版本:只安装 4.18.2
    "lodash": "^4.17.21",    // 兼容版本:4.x. x(最常用)
    "axios": "~1.6.0",       // 近似版本:1. 6.x
    "moment": "*",           // 任意版本(不推荐)
    "react": ">=18.0.0",     // 大于等于指定版本
    "vue": "18.0.0 - 19.0.0" // 版本范围
  }
}

版本符号速记

|-----|------|-----------|------------------|
| 符号 | 含义 | 示例 | 匹配范围 |
| 无符号 | 精确版本 | 1.2.3 | 只匹配 1. 2.3 |
| ^ | 兼容版本 | ^1. 2.3 | 1.2.3 到 <2.0.0 |
| ~ | 近似版本 | ~1.2. 3 | 1.2.3 到 <1. 3.0 |
| * | 任意版本 | * | 所有版本 |


第八部分:常用工作流程

🆕 开始新项目

复制代码
# 使用 Bun(推荐)
mkdir my-project && cd my-project
bun init -y
bun add express
bun add -d typescript @types/node @types/express

# 创建 tsconfig.json
bunx tsc --init

👥 克隆已有项目

复制代码
git clone <仓库地址>
cd <项目目录>

# 安装依赖(二选一)
npm install    # 如果项目用 npm
bun install    # 更快,兼容 npm 项目

# 启动开发
npm run dev
bun dev

📦 发布自己的 npm 包

复制代码
# 1. 登录 npm
npm login

# 2. 检查包名是否可用
npm search <包名>

# 3. 发布
npm publish

# 4. 更新版本并发布
npm version patch   # 1.0.0 -> 1.0.1
npm version minor   # 1.0.0 -> 1. 1.0
npm version major   # 1.0.0 -> 2. 0.0
npm publish

第九部分:实用技巧

1. 查看包信息

复制代码
# 查看包的详细信息
npm info lodash
npm view lodash versions   # 查看所有版本

# 查看已安装的包
npm list
npm list --depth=0         # 只看顶层依赖
bun pm ls

2. 清理与重装

复制代码
# 删除 node_modules 并重装
rm -rf node_modules
npm install
# 或
bun install

# npm 清理缓存
npm cache clean --force

3. 使用国内镜像加速

复制代码
# npm 设置淘宝镜像
npm config set registry https://registry.npmmirror.com

# 查看当前镜像
npm config get registry

# 恢复官方镜像
npm config set registry https://registry.npmjs.org

# Bun 设置镜像
bun config set registry https://registry.npmmirror.com

4. 检查安全漏洞

复制代码
# npm
npm audit              # 检查漏洞
npm audit fix          # 自动修复
npm audit fix --force  # 强制修复(可能有破坏性更新)

第十部分:完整命令速查表

项目管理

|--------|--------------------|------------------|
| 操作 | npm | Bun |
| 初始化项目 | npm init -y | bun init -y |
| 安装所有依赖 | npm install | bun install |
| 运行脚本 | npm run <script> | bun <script> |
| 执行命令 | npx <command> | bunx <command> |

依赖管理

|--------|------------------------|--------------------|
| 操作 | npm | Bun |
| 添加依赖 | npm install <pkg> | bun add <pkg> |
| 添加开发依赖 | npm install -D <pkg> | bun add -d <pkg> |
| 全局安装 | npm install -g <pkg> | bun add -g <pkg> |
| 移除依赖 | npm uninstall <pkg> | bun remove <pkg> |
| 更新依赖 | npm update | bun update |
| 查看过期包 | npm outdated | bun outdated |

运行代码

|-------|------------------------|-----------------------|
| 操作 | npm/Node | Bun |
| 运行 JS | node file.js | bun file.js |
| 运行 TS | 需要 ts-node | bun file.ts |
| 热重载 | node --watch file.js | bun --watch file.ts |
| 运行测试 | npm test | bun test |


总结

核心要点

复制代码
┌─────────────────────────────────────────────────────────┐
│                    记住这些就够了                         │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  📦 安装依赖:bun add <包名>                             │
│                                                         │
│  🗑️ 卸载依赖:bun remove <包名>                          │
│                                                         │
│  🚀 运行脚本:bun <脚本名>                               │
│                                                         │
│  📄 运行文件:bun <文件名>(支持 . ts/. tsx)              │
│                                                         │
│  ⚡ 执行命令:bunx <命令>                                │
│                                                         │
└─────────────────────────────────────────────────────────┘

我的建议

  1. 新项目优先使用 Bun:速度快,原生支持 TypeScript
  2. 老项目可以混用 :用 bun install 加速,用 npm run 执行脚本
  3. 掌握 package.json:这是所有项目的核心配置文件
  4. 善用 bunx/ npx:临时使用工具无需全局安装

现在,你已经掌握了 npm 和 Bun 的核心用法,可以开始实际开发了!🚀


最后更新:2025 年 12 月

相关推荐
崔庆才丨静觅3 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60614 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了4 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅4 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅4 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅5 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment5 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅5 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊5 小时前
jwt介绍
前端
爱敲代码的小鱼5 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax