跳到主要内容

Rollup

Rollup 是现代前端构建谱系里很关键的一环。很多人日常写项目时不直接碰它,但理解库构建、Tree Shaking、插件链路时,很难绕开它。

Rollup 最适合做什么

它最擅长的是模块产物整理,尤其是:

  • JavaScript / TypeScript 库构建
  • ESM / CJS 多格式输出
  • Tree Shaking
  • 插件驱动的产物处理

为什么它还值得单独学

即使很多应用项目已经转到 Vite、Rsbuild、Next、Turbopack,Rollup 仍然重要,因为:

  • Vite 的构建主线长期依赖过它
  • 很多组件库、工具库、SDK 仍然直接使用它
  • 它的插件体系影响了很多后来的工具设计

一个最常见的配置

import typescript from '@rollup/plugin-typescript'
import { defineConfig } from 'rollup'

export default defineConfig({
input: 'src/index.ts',
output: [
{
file: 'dist/index.esm.js',
format: 'esm',
sourcemap: true,
},
{
file: 'dist/index.cjs.js',
format: 'cjs',
sourcemap: true,
},
],
plugins: [typescript()],
external: ['react', 'react-dom'],
})

一个更进阶的配置参考

import resolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import babel from '@rollup/plugin-babel'
import typescript from '@rollup/plugin-typescript'
import terser from '@rollup/plugin-terser'
import dts from 'rollup-plugin-dts'

export default [
{
input: 'src/index.ts',
output: [
{ file: 'dist/index.mjs', format: 'esm', sourcemap: true },
{ file: 'dist/index.cjs', format: 'cjs', sourcemap: true, exports: 'named' },
],
external: ['react', 'react-dom'],
plugins: [
resolve(),
commonjs(),
typescript({ tsconfig: './tsconfig.json' }),
babel({ babelHelpers: 'bundled', extensions: ['.ts', '.tsx', '.js'] }),
terser(),
],
},
{
input: 'src/index.ts',
output: [{ file: 'dist/index.d.ts', format: 'es' }],
plugins: [dts()],
},
]

这类配置通常会出现在:

  • React 组件库
  • SDK
  • 工具库
  • 需要产出类型定义和双格式产物的 npm 包

前端项目里怎么接 Rollup

应用项目通常不会直接从 Rollup 起步,但库项目里很常见。尤其是这些场景:

1. React 组件库

  • 入口文件统一导出组件
  • reactreact-dom 作为 external
  • 输出 esmcjs
  • 样式单独处理或跟着构建走

2. 工具库

  • 只关心 TypeScript 到产物的转换
  • 更在意包体积和 Tree Shaking
  • 对浏览器直接运行要求不高

3. SDK

  • 需要按不同目标环境输出不同格式
  • 需要控制 external、globals 和 bundle 结构

Plugin 怎么看

Rollup 的插件体系是它最重要的一层扩展点。

常见插件会处理这些事:

  • TypeScript
  • Babel
  • CommonJS 转换
  • Node 模块解析
  • JSON 导入
  • terser 压缩

external 为什么重要

做库时,external 经常是最值得确认的一层。

external: ['react', 'react-dom']

如果这些依赖没有排除,最终产物可能会把本不该打进去的运行时一起带上,导致:

  • 包体积变大
  • 宿主项目重复依赖
  • React 多实例问题

Rollup 最适合放在哪里理解

  • 不太像全能型应用构建器
  • 更像精于产物输出和模块打包的一把工具刀

如果当前目标是做应用项目,通常不会先单独选 Rollup;如果目标是做库、做 SDK、理解 bundler 机制,它非常值得补。