Vite 打包用的就是这个 Rollup

268 阅读1分钟

Screenshot 2024-08-16 at 16.15.55.png

vite 是使用 rollup 来进行打包

本来想写一下如何使用 rollup,但看了 rollup 官方教程后感觉没有必要了。它这个写得非常清晰了,跟着做一遍就可以对 rollup 有一个基本的理解

官方中文教程:cn.rollupjs.org/tutorial/

总结几个点

打包

# 全局安装
npm install rollup --global

# 可以使用 rollup 命令
rollup

# 将 main.js 作为入口打包,目标文件是 bundle.js,格式是 CommonJS
rollup main.js --file bundle.js --format cjs

使用配置文件

// rollup.config.mjs
export default {
	input: "src/main.js",
	output: {
		file: "bundle.js",
		format: "cjs",
	},
};
# 指定配置文件来运行 rollup
rollup --config rollup.config.mjs

使用插件

利用插件,可以让 rollup 处理更复杂的打包行为

插件列表:github.com/rollup/awes…

JSON 插件
# 安装 json 插件
npm install --save-dev @rollup/plugin-json
// 在 main.js 中导入 json 文件

// src/main.js
import { version } from "../package.json";

export default function () {
	console.log("version " + version);
}
// 更新配置

// rollup.config.mjs
import json from '@rollup/plugin-json';

export default {
	input: 'src/main.js',
	output: {
		file: 'bundle.js',
		format: 'cjs'
	},
	plugins: [json()]
};
压缩代码插件
# 安装 terser 插件
npm install --save-dev @rollup/plugin-terser
// 导出一份 bundle.min.js

// rollup.config.mjs
import json from '@rollup/plugin-json';
import terser from '@rollup/plugin-terser';

export default {
	input: 'src/main.js',
	output: [
		{
			file: 'bundle.js',
			format: 'cjs'
		},
		{
			file: 'bundle.min.js',
			format: 'iife',
			name: 'version',
			plugins: [terser()]
		}
	],
	plugins: [json()]
};
代码分割
// 动态导入

// src/main.js
export default function () {
	import("./foo.js").then(({ default: foo }) => console.log(foo));
}
# 执行 rollup 时,设置导出文件夹 以明确导出文件之间的相对位置
rollup src/main.js -f cjs -d dist

# 最终生产 dist/main.js 及 dist/chunk-[hash].js

更多 Rollup 内容可以查看官方指南:cn.rollupjs.org/command-lin…