推荐答案
Rollup 的核心概念包括:
- 入口文件(Entry Point):指定 Rollup 打包的起点文件。
- 输出文件(Output):定义打包后的文件输出路径和格式。
- 插件(Plugins):用于扩展 Rollup 的功能,如处理非 JavaScript 文件、压缩代码等。
- Tree Shaking:Rollup 通过静态分析移除未使用的代码,优化打包结果。
- 模块(Modules):Rollup 支持 ES 模块,能够将多个模块打包成一个文件。
- 代码分割(Code Splitting):Rollup 支持将代码分割成多个文件,优化加载性能。
本题详细解读
1. 入口文件(Entry Point)
入口文件是 Rollup 打包的起点,通常是一个 JavaScript 文件。Rollup 会从这个文件开始,分析依赖关系并打包所有相关的模块。
// rollup.config.js
export default {
input: 'src/main.js', // 入口文件
output: {
file: 'bundle.js', // 输出文件
format: 'iife' // 输出格式
}
};2. 输出文件(Output)
输出文件定义了打包后的文件输出路径和格式。Rollup 支持多种输出格式,如 iife(立即执行函数表达式)、cjs(CommonJS)、esm(ES 模块)等。
// www.javascriptcn.com code example
// rollup.config.js
export default {
input: 'src/main.js',
output: {
file: 'dist/bundle.js', // 输出路径
format: 'iife', // 输出格式
name: 'MyBundle' // 全局变量名
}
};3. 插件(Plugins)
插件是 Rollup 的核心扩展机制,允许开发者自定义打包过程。常见的插件包括 @rollup/plugin-node-resolve(用于解析 node_modules 中的模块)、@rollup/plugin-commonjs(将 CommonJS 模块转换为 ES 模块)等。
// www.javascriptcn.com code example
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
export default {
input: 'src/main.js',
output: {
file: 'bundle.js',
format: 'iife'
},
plugins: [
resolve(),
commonjs()
]
};4. Tree Shaking
Tree Shaking 是 Rollup 的一个重要特性,它通过静态分析移除未使用的代码,从而减少打包后的文件体积。这一特性依赖于 ES 模块的静态结构。
// www.javascriptcn.com code example
// math.js
export function square(x) {
return x * x;
}
export function cube(x) {
return x * x * x;
}
// main.js
import { cube } from './math.js';
console.log(cube(5)); // 125在上述例子中,square 函数不会被包含在最终的打包文件中,因为它没有被使用。
5. 模块(Modules)
Rollup 支持 ES 模块,能够将多个模块打包成一个文件。ES 模块的静态特性使得 Rollup 能够进行 Tree Shaking 和优化。
// www.javascriptcn.com code example
// math.js
export function add(a, b) {
return a + b;
}
// main.js
import { add } from './math.js';
console.log(add(2, 3)); // 56. 代码分割(Code Splitting)
Rollup 支持代码分割,允许将代码分割成多个文件,从而优化加载性能。这在大型应用中非常有用,可以减少初始加载时间。
// www.javascriptcn.com code example
// rollup.config.js
export default {
input: 'src/main.js',
output: {
dir: 'dist', // 输出目录
format: 'esm', // 输出格式
chunkFileNames: '[name].js' // 代码分割后的文件名
}
};通过代码分割,Rollup 可以将不同的模块打包成多个文件,并在需要时动态加载这些文件。