携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第30天,点击查看活动详情
概念
rollup就是和webpack一样,是工程化的打包工具,其优点就是生成的文件要比webpack更家精炼,一般开发项目使用webpack,创建js库使用rollup。
开始
- 初始化项目
npm init -y,生成ts配置文件tsc --init, - 根创建目录src文件夹,里面创建文件夹core/types/utils三个文件夹,
- 安装rollup和ts插件 ,rollup-plugin-typescripte2是babel一样的作用解析es语法,rollup-plugin-dts打包声明文件的插件
npm install rollup rollup-plugin-dts rollup-plugin-typescript2 rollup-plugin-clear typescript -D
- 修改tsconfig.js里的module属性值为
ESNext - 根目录创建rollup.config.js,配置input(对应webpack的entry)/output(wepback的output)/plugin,整个导出一个数组,说明要打包两次,一次是js文件打包,一次是ts类型打包,入口是src/core/index.ts,告诉rollup从这个文件开始解析,output是一个数组,打包产物为3种格式,因为是js库,所以要满足各种需要的用户。es是import导入,cjs是require导入,umd是script导入,第二次打包只是针对es方式使用,打包个类型声明文件。
import path from 'path'
import ts from 'rollup-plugin-typescript2'
import dts from 'rollup-plugin-dts'
import clear from 'rollup-plugin-clear'
export default [{
input: "./src/core/index.ts",
output: [{
file: path.resolve(__dirname, './dist/index.esm.js'),
format: "es",
}, {
file: path.resolve(__dirname, './dist/index.cjs.js'),
format: "cjs"
}, {
file: path.resolve(__dirname, './dist/index.js'),
format: "umd",
name: "tracker"
}],
plugins: [clear({
targets: ["dist"]
}),
ts({
include: "src/**/*.ts",
exclude: "node_modules/**",
}),
]
}, {
input: "./src/core/index.ts",
output: {
file: path.resolve(__dirname, './dist/index.d.ts'),
format: 'es',
},
plugins: [dts()]
}]
- 最后修改package.json,在script脚本里加上一句
"build": "rollup -c",如果指定配置文件,可以在后面跟上配置文件路径,当前配置文件在根目录,所以可以省略了。
...
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "rollup -c"
},
...
- 在src/index.ts里随便写点测试代码,
export const a = 123;
console.log(a);
执行npm run build ,根目录生成了dist文件,里面有所有输出的类型后缀的文件,就ok了
rollup.config.js里面配置很多,可以根据实际情况来优化打包配置。
// rollup.config.js
export default {
// 核心选项
input, // 必须
external,
plugins,
// 额外选项
onwarn,
// danger zone
acorn,
context,
moduleContext,
legacy
output: { // 必须 (如果要输出多个,可以是一个数组)
// 核心选项
file, // 必须
format, // 必须
name,
globals,
// 额外选项
paths,
banner,
footer,
intro,
outro,
sourcemap,
sourcemapFile,
interop,
// 高危选项
exports,
amd,
indent
strict
},
};