初学 rollup
我对 rollup 的理解
你可以在 js 文件中可以使用 ES6 模块化语法,来导入导出文件。然后,你可以配置 rollup 打包这些文件打包为什么格式。
有 es、amd、cjs、iife、umd、system 这 5 中格式。
比如在一个 demo 目录下,有一个入口文件:
demo/main.js
js
import {getSum} from './math'
const sum = getSum(10, 10)
console.log(sum)
export default sum还有一个 demo/math.js
js
export function getSum(x, y) {
return x + y
}还有一个 demo/index.html
html
<!DOCTYPE html>
<body>
hello
</body>
<script type="module" src="./main.js"></script>
</html>打开 index.html,你会看到控制台打印了 20。
如果不加 type="module",那么会报下面的错误:
caught SyntaxError: Cannot use import statement outside a module
这是因为 main.js 中使用了 es module 模块化语法,script 标签需要设置 type="module" 才能对其语法进行识别。
使用 rollup 打包 4 中格式
在 demo 下
pnpm init,然后pnpm add rollup -D
创建配置文件 rollup.config.js
js
export default {
input: "main.js",
output: [
{
file: "dist/index.umd.js",
format: "umd", // 浏览器和 node 都支持
name: "test"
},
{
file: "dist/index.esm.js",
format: "es", // es 模块化。在第三方支持 es 模块化导出的构建工具中,我们可能需要用到模块化导出。
name: "test"
},
{
file: "dist/index.common.js",
format: "cjs", // 只有 node 支持
name: "test"
},
{
file: "dist/index.iife.js",
format: "iife", // 只有 浏览器 支持
name: "test"
},
]
}配置脚本
json
{
"build": "rollup -c" // -c 后面接配置文件路径,默认为项目根目录下的 rollup.config.js
}然后执行打包,就可以看到 4 种不同的打包格式了。