Rollup 浅析

画个重点 开发应用时使用 Webpack,开发库时使用 Rollup

Rollup

https://www.rollupjs.com/

Rollup 是一个 JavaScript 模块打包器,可以将小块代码编译成大块复杂的代码,例如 library 或应用程序

  • 通过 rollup 打包后的代码,相比与 webpack 打出来的包体积会更小,而且代码会更加简洁,不会有过多的冗余代码。

  • rollup 也对 es 模块输出及 iife 格式打包有很好的支持

  • Tree Shaking: 自动移除未使用的代码, 输出更小的文件

  • Scope Hoisting: 所有模块构建在一个函数内, 执行效率更高

  • Config 文件支持通过 ESM 模块格式书写

  • 可以一次输出多种格式:

    • 不用的模块规范: IIFE, AMD, CJS, UMD, ESM
    • Development 与 production 版本: .js, .min.js
  • 文档精简

构建UMD

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import typescript from 'rollup-plugin-typescript2';
import { version } from './package.json';

export default {
input: 'src/utils.ts', // 入口文件
output: {
name: 'my_utils', // umd 模式必须要有 name 此属性作为全局变量访问打包结果
file: `dist/@${version}/index.js`,
format: 'umd',
sourcemap: true,
},
plugins: [
typescript({
tsconfigOverride: {
compilerOptions: {
declaration: false, // 输出时去除类型文件
},
},
}),
],
};
rollup -c

babel 编译

1
npm i -D @babel/core @babel/plugin-transform-runtime @babel/preset-env @rollup/plugin-babel @babel/preset-typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//.babelrc
{
"presets": [
[
"@babel/preset-env",
{
"modules": false,
"loose": true,
"targets": {
"browsers": "> 1%, IE 11, not op_mini all, not dead",
"node": 8
}
}
],
["@babel/preset-typeScript"]
]
}

// rollup.config
import { babel } from '@rollup/plugin-babel';
plugins:[
babel({
extensions: [".js", ".ts"],
exclude: "node_modules/**",
babelHelpers: 'bundled'
}),
]

压缩

1
2
3
4
5
6
7
8
// sh
npm install -D rollup-plugin-terser

// rollup.config.js
import { terser } from 'rollup-plugin-terser';
plugins: [
terser(),
]

打包库常用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import resolve from 'rollup-plugin-node-resolve' // 告诉 Rollup 如何查找外部模块
import commonjs from 'rollup-plugin-commonjs' // 将CommonJS模块转换为 ES2015 供 Rollup 处理
import vue from 'rollup-plugin-vue' // 处理vue文件
import babel from 'rollup-plugin-babel' // rollup 的 babel 插件,ES6转ES5
import css from 'rollup-plugin-css-only' // 提取css,压缩能力不行
import CleanCSS from 'clean-css' // 压缩css
import { writeFileSync } from 'fs' // 写文件
export default {
//目录
input: 'index.js',
output: {
name:'crud',
file: 'bundle.js',
format: 'umd'
},
plugins: [
resolve({ extensions: ['.vue'] }),
commonjs(),
vue(),
babel(),
css({ output(style) {
// 压缩 css 写入 dist/vue-rollup-component-template.css
writeFileSync('dist/vue-rollup-component-template.css', new CleanCSS().minify(style).styles)
} }),
// css: false 将<style>块转换为导入语句,rollup-plugin-css-only可以提取.vue文件中的样式
vue({ css: false }),
]
};

基础插件