Rollup 从0到1:TypeScript打包完全指南

一、什么是Rollup?

Rollup是一个专注于JavaScript模块打包的工具,特别适合构建库类项目。它的核心优势是强大的"树摇"(Tree-shaking)能力,能有效移除未使用的代码,生成精简的输出。对于TypeScript项目,Rollup可以通过插件轻松集成TS编译能力。

二、安装环境与依赖

首先确保已安装Node.js(v14+),然后创建项目并安装依赖:

bash 复制代码
# 创建项目目录
mkdir rollup-ts-demo && cd rollup-ts-demo
npm init -y

# 安装核心依赖
npm install rollup --save-dev

# 安装TypeScript相关依赖
npm install typescript @rollup/plugin-typescript tslib --save-dev

# 安装其他实用插件
npm install @rollup/plugin-node-resolve @rollup/plugin-commonjs --save-dev
  • typescript:TypeScript编译器
  • @rollup/plugin-typescript:Rollup的TypeScript插件
  • tslib:提供TypeScript辅助函数(如__extends
  • @rollup/plugin-node-resolve:解析node_modules中的模块
  • @rollup/plugin-commonjs:转换CommonJS模块为ES模块

三、TypeScript配置

在项目根目录创建tsconfig.json

json 复制代码
{
  "compilerOptions": {
    "target": "ES6",                          // 编译目标版本
    "module": "ESNext",                       // 模块系统
    "outDir": "dist",                         // 输出目录
    "rootDir": "src",                         // 源代码根目录
    "strict": true,                           // 开启严格模式
    "esModuleInterop": true,                  // 允许ES模块与CommonJS互操作
    "skipLibCheck": true,                     // 跳过库文件检查
    "forceConsistentCasingInFileNames": true  // 强制文件名大小写一致
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

四、创建TypeScript项目

1. 项目结构
bash 复制代码
rollup-ts-demo/
├── src/
│   ├── math.ts       # 工具函数模块
│   └── index.ts      # 入口文件
├── rollup.config.js  # Rollup配置文件
└── tsconfig.json     # TypeScript配置文件
2. 编写TypeScript代码

src/math.ts(带类型注解的工具模块):

typescript 复制代码
// 加法函数(带类型注解)
export const add = (a: number, b: number): number => a + b;

// 乘法函数(带类型注解)
export const multiply = (a: number, b: number): number => a * b;

// 格式化数字(带默认参数)
export const formatNumber = (num: number, precision: number = 2): string => {
  return num.toFixed(precision);
};

// 未被使用的函数(会被Tree-shaking移除)
export const unusedFunction = (): string => {
  return "这段代码不会出现在最终打包结果中";
};

src/index.ts(入口文件):

typescript 复制代码
// 只导入需要的函数
import { add, multiply, formatNumber } from './math';

// 导出供外部使用
export default {
  add,
  multiply,
  formatNumber
};

五、配置Rollup

创建rollup.config.mjs配置文件:

javascript 复制代码
import typescript from '@rollup/plugin-typescript';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';

export default {
  // 入口文件
  input: 'src/index.ts',
  
  // 外部依赖(不打包到结果中)
  external: [],
  
  // 插件配置
  plugins: [
    // 解析第三方模块
    resolve(),
    // 转换CommonJS模块为ES模块
    commonjs(),
    // TypeScript编译配置
    typescript({
      tsconfig: './tsconfig.json', // 指定TS配置文件
      declaration: true,           // 生成.d.ts类型声明文件
      declarationDir: 'dist/types' // 类型声明文件输出目录
    })
  ],
  
  // 输出配置(支持多格式输出)
  output: [
    {
      // ES模块格式(适合现代浏览器和ES模块环境)
      file: 'dist/bundle.esm.js',
      format: 'es',
      sourcemap: true // 生成sourcemap,方便调试
    },
    {
      // CommonJS格式(适合Node.js环境)
      file: 'dist/bundle.cjs.js',
      format: 'cjs',
      sourcemap: true
    },
    {
      // UMD格式(通用模块定义,支持浏览器全局变量和AMD)
      file: 'dist/bundle.umd.js',
      format: 'umd',
      name: 'MathUtils', // 全局变量名
      sourcemap: true
    }
  ]
};

六、添加打包脚本

修改package.json,添加构建脚本:

json 复制代码
{
  "scripts": {
    "build": "rollup -c",        // 执行打包
    "watch": "rollup -c -w"      // 监听模式,文件变化自动重新打包
  }
}

七、执行打包

运行以下命令执行打包:

bash 复制代码
npm run build

打包成功后,会生成dist目录,包含:

  • 三种格式的JS文件(esm、cjs、umd)
  • 对应的sourcemap文件(.map)
  • types目录(包含类型声明文件)

八、查看打包结果

dist/bundle.esm.js(精简的ES模块输出):

javascript 复制代码
const add = (a, b) => a + b;

const multiply = (a, b) => a * b;

const formatNumber = (num, precision = 2) => {
  return num.toFixed(precision);
};

export default {
  add,
  multiply,
  formatNumber
};

可以看到,未使用的unusedFunction已被自动剔除(Tree-shaking效果)

dist/types/index.d.ts(生成的类型声明文件):

typescript 复制代码
import { add, multiply, formatNumber } from './math';
declare const _default: {
    add: typeof add;
    multiply: typeof multiply;
    formatNumber: typeof formatNumber;
};
export default _default;

九、使用打包结果

  1. 在ES模块环境中
javascript 复制代码
import MathUtils from './dist/bundle.esm.js';
console.log(MathUtils.add(2, 3)); // 输出: 5
  1. 在Node.js中
javascript 复制代码
const MathUtils = require('./dist/bundle.cjs.js');
console.log(MathUtils.multiply(2, 3)); // 输出: 6
  1. 在浏览器中
html 复制代码
<script src="./dist/bundle.umd.js"></script>
<script>
  console.log(MathUtils.formatNumber(3.14159)); // 输出: "3.14"
</script>

十、总结

通过本教程,你已经掌握了:

  1. Rollup+TypeScript的基础配置
  2. 多格式输出(ES模块、CommonJS、UMD)
  3. 类型声明文件的生成
  4. 树摇优化的实际效果

Rollup特别适合TypeScript库的打包,它能生成干净、精简的代码,同时保留完整的类型信息,为使用者提供良好的开发体验。

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