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库的打包,它能生成干净、精简的代码,同时保留完整的类型信息,为使用者提供良好的开发体验。

相关推荐
Glink3 分钟前
从零开始编写自己的AI账单Agent
前端·agent·ai编程
Hilaku3 分钟前
我是如何用一行 JS 代码,让你的浏览器内存瞬间崩溃的?
前端·javascript·node.js
努力犯错玩AI3 分钟前
如何在ComfyUI中使用Qwen-Image-Layered GGUF:完整安装和使用指南
前端·人工智能
Lefan6 分钟前
在浏览器中运行大模型:基于 WebGPU 的本地 LLM 应用深度解析
前端
五仁火烧6 分钟前
npm run build命令详解
前端·vue.js·npm·node.js
哈__8 分钟前
React Native 鸿蒙跨平台开发:简易记事本 APP
javascript·react native·react.js
贺今宵9 分钟前
electron-vue无网络环境,读取本地图片/文件展示在页面vue中protocol
前端·javascript·electron
IT_陈寒9 分钟前
SpringBoot 3.x实战:5个高效开发技巧让我减少了40%重复代码
前端·人工智能·后端
noodles102412 分钟前
iOS下怎么就找不到好用的新手引导组件呢?还是得自己动手
前端
不务正业的前端学徒12 分钟前
vue2/3 watch原理
前端