一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第7天,点击查看活动详情。
1.rollup简介
Rollup 是一个 JavaScript 模块打包器,可以将小块代码编译成大块复杂的代码,例如 library 或应用程序。Rollup 对代码模块使用新的标准化格式,这些标准都包含在 JavaScript 的 ES6 版本中,而不是以前的特殊解决方案,如 CommonJS 和 AMD。ES6 模块可以使你自由、无缝地使用你最喜爱的 library 中那些最有用独立函数,而你的项目不必携带其他未使用的代码。ES6 模块最终还是要由浏览器原生实现,但当前 Rollup 可以使你提前体验。
2.使用
2.1项目配置
- 初始化一个默认项目
npm init
- 采用全局安装
npm i rollup -g
或者指定需要使用rollup的目录中安装npm i rollup
- 根目录新建一个
rollup.config.js
用于写入自定义配置 - 配置
package.json
操作命令rollup --config rollup.config.js
2.2 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\
},\
};
2.3 简单配置
export default {
input: "index.js",
output: [
{
file: "dist/index.umd.js",
format: "umd",
name: "UmdBundle",
},
{
file: "dist/index.cjs.js",
format: "cjs",
name: "CjsBundle",
},
{
file: "dist/index.iife.js",
format: "iife",
name: "IifeBundle",
},
{
file: "dist/index.esm.js",
format: "esm",
name: "EsmBundle",
},
{
file: "dist/index.amd.js",
format: "amd",
name: "AmdBundle",
},
{
file: "dist/index.system.js",
format: "system",
name: "SystemBundle",
},
],
};
3 常用插件
可参考官网插件仓库:github.com/rollup/plug…
3.1.@rollup/plugin-node-resolve
index.js
import dayjs from "dayjs";
console.log(dayjs("2018-04-04T16:00:00.000Z"));
使用index.html引入打包后的esm代码
<head>
<script src="./chapter2/dist/index.umd.js"></script>
</head>
下图面型爆出了dayjs这个包不存在 这个时候打包的时候,发现控制台有两句警告,一是说dayjs少了全局变量,第二是没有解决内部依赖,其实意思是你的dayjs包没有打包进输出文件中
方法一: 那么解决方法有两个,一是引入外部的dayjs数据
<head>
<script src="https://cdn.bootcdn.net/ajax/libs/dayjs/1.11.0/dayjs.min.js"></script>
<script src="./chapter2/dist/index.umd.js"></script>
</head>
控制台就正常打印出来这个,dayjs
其实是output的name配置展示的名称
方法2: 使用@rollup/plugin-node-resolve
(1)安装插件:npm i @rollup/plugin-node-resolve
(2)配置插件rollup.config.js
(3)npm run build
控制台报错。
(4)可以看出dayjs的nodemoudle没有到处defalut,没找到,查看dayjs的nodemodule的dayjs使用的commonjs规范,也就是说这个插件功能很单一只会打印esmodule的模式,那就需要先使用下面说到的commonjs打包插件解决。
3.2.@rollup/plugin-commonjs
通过上图的配置后,就能正常运行了,可以明显看出dayjs的部分代码已经打入了包里
3.3 @rollup/plugin-json
想用json数据
import dataJson from "./data.json";
console.log(dataJson);
打包的时候报错
解决方式很简单,直接调用插件即可
3.4 rollup-plugin-typescript2
现在项目中都是TS开发了,所以我们开发TS的时候,需要根据tsConfig.json进行打包后的代码控制,比如是es5等等,具体的详细配置建议看插件官网。
// ts
import ts from 'rollup-plugin-typescript2'
const extensions = ['.js', '.ts', '.tsx']
const tsPlugin = ts({
tsconfig: path.resolve('./tsconfig.json'), // 导入本地ts配置
extensions,
exclude: ['**/__tests__']
})
plugins: [ tsPlugin],
3.5 rollup-plugin-terser
压缩代码,将空格等格式全部压缩
import { terser } from 'rollup-plugin-terser'
plugins: [ terser()],
如图全部压缩到一行去了