使用 rollup 打包 react 库

本文最后更新于:2020年12月13日 晚上

场景

其实一般用 tsc 编译一下就行了,但如果想要更加强大的功能,例如打包成一个单文件、多种格式、或者包含 css 时,就需要使用 rollup 来处理了。

  • 打包
  • 处理 ts
  • 处理 css
  • 压缩

配置文件

package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"scripts": {
"pub": "yarn build && lerna bootstrap",
"build": "rollup -c rollup.config.js"
},
"devDependencies": {
"@types/react": "^16.9.48",
"moment": "^2.27.0",
"rollup": "^2.26.9",
"rollup-plugin-babel": "^4.4.0",
"rollup-plugin-postcss": "^3.1.8",
"rollup-plugin-terser": "^7.0.1",
"rollup-plugin-typescript2": "^0.27.2",
"typescript": "3.8.2"
}
}

rollup.config.js

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
29
30
31
32
33
34
35
36
import babel from "rollup-plugin-babel";
import typescript from "rollup-plugin-typescript2";
import pkg from "./package.json";
import { terser } from "rollup-plugin-terser";
import postcss from "rollup-plugin-postcss";
import { resolve } from "path";

export default {
// 入口文件
input: resolve(__dirname, "./src/index.ts"),
output: {
// 打包名称
name: pkg.name,
exports: "named",
file: resolve(__dirname, "./dist/index.js"),
format: "es",
},
external: [
...Object.keys(pkg.dependencies || {}),
...Object.keys(pkg.peerDependencies || {}),
],
plugins: [
babel({
exclude: "node_modules/**",
}),
typescript({
typescript: require("typescript"),
}),
postcss({
sourceMap: true,
extract: true,
minimize: true,
}),
terser(), // minifies generated bundles
],
};