Rollup

2022-01-16  本文已影响0人  JerrySi

esm的打包器,更为小巧,不支持类似HRM高级特性。
提供一个充分利用ESM各项特性的高效打包器。

1. 使用Rollup, Rollup自动支持Tree-Sharking

rollup.config.js也是运行在node环境中, 但是Rollup会直接处理这个配置文件, 所以配置文件里面可以是esm语法

yarn add rollup --dev
// 输入文件:./src/index.js 
// 输出格式:--format iife(浏览器格式:自执行函数格式)
// 输出文件:--file dist/bunlde.js
yarn rollup ./src/index.js --format iife --file dist/bunlde.js

// 配置文件 rollup.config.js
// 默认不走config,需要指定 --config
// 命令 rollup --config
// 命令 rollup --config ./rollup.config.js
export default {
  input:  "./src/index.js",
  output: {
    file: "dist/bundle.js",
    format: "iife"
  }
}

2. 插件, 插件是Rollup唯一的扩展方式

// 处理json文件
import json from "rollup-plugin-json"
// 加载npm模块, 默认不会找到路径
import resolve from "rollup-plugin-node-resolve"
// 加载commonJS模块
import commonjs from "rollup-plugin-commonjs"

export default {
  input:  "./src/index.js",
  output: {
    file: "dist/bundle.js",
    format: "amd"
  },
  plugins:[
    json(),
    resolve(),
    commonjs()
  ]
}

3. 代码拆分

export default {
  input: "./src/index.js",
  output: {
    // 拆分需要输出多个文件, 这里指定是文件目录
    dir: "dist",
    // 模块打包只能commonJS或者AMD格式, 为什么不能esm?
    format: "amd" 
  }
}

import("./logger.js").then(({log}) => {})

4. 多入口文件打包

export default {
  //input: ["a.js", "b.js"]
  input: {
    index:  "index.js",
    foo: "foo.js"
  },
  output: {
    dir: "dist",
    format: "amd", // 打包完后,浏览器环境依赖require.js等实现amd规范的库
  }
}
 
// index.html
  <!-- AMD 标准格式的输出 bundle 不能直接引用 -->
  <!-- <script src="foo.js"></script> -->
  <!-- 需要 Require.js 这样的库 -->
  <script src="https://unpkg.com/requirejs@2.3.6/require.js" data-main="foo.js"></script>
  • 优点
    适合开发框架和类库
    输出的结果更扁平,执行效率更高
    自动移除未引用代码
    打包结果依然完全可读
  • 缺点
    加载非esm第三方模块比较复杂
    模块最终被打包到一个函数中,无法实现HMR
    浏览器环境中,代码拆分依赖AMD库
上一篇 下一篇

猜你喜欢

热点阅读