Rollup 打包工具入门:配置、插件与多入口实战

作者:清欢

时间:2026-10-26

浏览:340

本文详解 Rollup 打包工具的核心特性与使用方法。内容涵盖 Rollup 与 Webpack 的对比、基础安装与命令行用法、rollup.config.js 配置文件编写。重点讲解如何通过插件处理 NPM 模块与 CommonJS,以及代码拆分和多入口打包的高级配置,最后对比 Parcel 提供选型建议。

文章目录

Rollup 介绍及使用

1、Rollup 概述

  • Rollup 是一个专注于 ES Module 的打包工具。
  • 其功能与 Webpack 相似,但体积更加轻量。
  • Rollup 不支持类似 Webpack 的 HRM(热模块替换)功能。

其设计初衷是提供一个能充分利用 ES Module 特性的高效打包解决方案。

2、Rollup 快速上手

安装:yarn add rolluo --dev
用法:
    yarn rollup  //不传递任何参数的情况下,打印Rollup的帮助信息
    yarn rollup ./src/index.js --format iife //执行index.js文件并以iife(自调用函数)的方式输出(--format指定输出格式)
    yarn rollup ./src/index.js --format iife --file dist/bundle.js //输出文件到dist/bundle.js
默认开启chunk去掉多余代码,优化输出结果

3、Rollup 配置文件

rollup.config.js

export default {
input: 'src/index.js',
    output: {
        file: 'dist/bundle.js',
        format: 'iife'
    }
}

4、Rollup 使用插件

插件机制是扩展 Rollup 功能的主要途径。

rollup.config.js

5、Rollup 加载 NPM 模块

默认情况下,Rollup 仅支持通过文件路径加载本地模块,无法直接通过模块名称导入第三方库。

rollup-plugin-node-resolve:安装后Rollup可直接通过模块名称导入模块
安装:yarn add rollup-plugin-node-resolve --dev

rollup.config.js

import resolvefrom 'rollup-plugin-node-resolve'
export default {
input: 'src/index.js',
    output: {
        file: 'dist/bundle.js',
format: 'iife'
    },
    plugins: [
        resolve()
    ]
}

6、Rollup 加载 CommonJS 模块

使用 rollup-plugin-commonjs 插件,可使 Rollup 兼容处理 CommonJS 格式的模块。

安装:yarn add rollup-plugin-commonjs --dev

rollup.config.js

import commonjsfrom 'rollup-plugin-commonjs'
export default {
input: 'src/index.js',
    output: {
        file: 'dist/bundle.js',
format: 'iife'
    },
    plugins: [
        commonjs()
    ]
}

7、Rollup 代码拆分

运行:yarn rollup

index.js

import('./logger').then(({ log }) => {
    log('code splitting~')
})

rollup.config.js

export default {
	input: 'src/index.js',
	  output: {
	      dir: 'dist',
	      format: 'amd'
  }
}

8、Rollup 多入口打包

多入口打包功能会自动提取公共模块,底层依赖于代码拆分机制。

rollup.config.js

方式1:

export default {
input: ['src/index.js', 'src/album.js'],
    output: {
        dir: 'dist',
        format: 'amd'
    }
}

方式2:

export default {
input: {
        foo: 'src/index.js',
        bar: 'src/album.js'
    },
output: {
dir: 'dist',
        format: 'amd'
    }
}

9、Rollup 选用原则

Rollup 的优势包括:输出结果更为扁平,执行效率更高;自动移除未引用的代码;打包后的代码保持完全可读,与手写代码风格一致。

Rollup 的局限性在于:加载非 ESM 格式的第三方模块较为复杂,需配置大量插件;所有模块最终被打包进单一函数,无法实现 HMR;在浏览器环境中,代码拆分功能依赖 AMD 库。

选型建议:开发应用程序时推荐使用 Webpack,因其功能全面;开发框架或类库时推荐 Rollup,因其轻量高效。

10、Parcel

Parcel 是一款零配置的前端应用打包器。

安装:

yarn add parcel-bundler --dev 

运行:

yarn parcel src/index.html 
//index.html为入口文件 

其优势包括:支持自动安装依赖、支持动态导入。在同等体量下,Parcel 打包速度通常快于 Webpack,这得益于其多进程并行工作机制,能充分发挥多核 CPU 性能(Webpack 也可通过 happypack 插件实现类似效果)。

以上就是 Rollup 简易入门示例教程的详细内容,更多关于 Rollup 入门教程的资料请关注本站其它相关文章!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章