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

相关推荐
李鸿耀29 分钟前
Flex 布局下文字省略不生效?原因其实很简单
前端
皮蛋瘦肉粥_1212 小时前
pink老师html5+css3day06
前端·css3·html5
华仔啊6 小时前
前端必看!12个JS神级简写技巧,代码效率直接飙升80%,告别加班!
前端·javascript
excel6 小时前
dep.ts 逐行解读
前端·javascript·vue.js
爱上妖精的尾巴6 小时前
5-20 WPS JS宏 every与some数组的[与或]迭代(数组的逻辑判断)
开发语言·前端·javascript·wps·js宏·jsa
excel6 小时前
Vue3 响应式核心源码全解析:Dep、Link 与 track/trigger 完整执行机制详解
前端
前端大卫6 小时前
一个关于时区的线上问题
前端·javascript·vue.js
whltaoin7 小时前
中秋赏月互动页面:用前端技术演绎传统节日之美
前端·javascript·html·css3·中秋主题前端
UrbanJazzerati7 小时前
考研英语深挖 “I wonder if it isn't...” —— 否定式疑问背后的肯定式锋利观点
面试
IT派同学7 小时前
TableWiz诞生记:一个被表格合并逼疯的程序员如何自救
前端·vue.js