Rollup

作者: 浅忆_0810 | 来源:发表于2021-06-30 23:03 被阅读0次

1. 介绍

Rollupwebpack作用类似,但Rollup更为小巧,仅仅是一款ESM打包器,Rollup中并不支持类似HMR这种高级特性

是为了提供一个充分利用ESM各种特性的高效打包器


2. 快速上手

2.1 安装Rollup

$ yarn add rollup -D
// index.js
// 导入模块成员
import { log } from './logger'
import messages from './messages'

// 使用模块成员
const msg = messages.hi

log(msg)
// logger.js
export const log = msg => {
  console.log('---------- INFO ----------')
  console.log(msg)
  console.log('--------------------------')
}

export const error = msg => {
  console.error('---------- ERROR ----------')
  console.error(msg)
  console.error('---------------------------')
}
// message.js
export default {
  hi: 'Hey Guys, I am zce~'
}

2.2 运行打包命令

$ yarn rollup ./index.js --file bundle.js

生成的bundle.js文件,代码如下

const log = msg => {
  console.log('---------- INFO ----------');
  console.log(msg);
  console.log('--------------------------');
};

var messages = {
  hi: 'Hey Guys, I am zce~'
};

// 导入模块成员

// 使用模块成员
const msg = messages.hi;

log(msg);

打包后的代码非常简洁,就是将需要运行的代码按顺序拼接到一起。注意,是只会保留到有用的代码。这就是Rollup最早提出的Tree-shaking特性,后来几乎被所有打包工具参考引入。


3. 配置文件

// rollup.config.js
export default {
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'iife' // 输出格式
  }
}

3.1 运行

$ yarn rollup --config

4. 使用插件

如:加载其它类型资源模块,导入CommosJS模块,编译ECMAScript新特性

注意:插件是Rollup唯一扩展途径

4.1 导入json文件

import json from 'rollup-plugin-json'

export default {
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'iife'
  },
  plugins: [
    json()
  ]
}

4.2 加载npm模块

import json from 'rollup-plugin-json'
import resolve from 'rollup-plugin-node-resolve'

export default {
    ...
  plugins: [
    json(),
    resolve()
  ]
}

4.3 加载CommosJS模块

import json from 'rollup-plugin-json'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'

export default {
  ...
  plugins: [
    json(),
    resolve(),
    commonjs()
  ]
}

5. 代码拆分

// index.js
import('./logger').then(({ log }) => {
  log('code splitting~')
})
// rollup.config.js
export default {
  input: 'src/index.js',
  output: {
    dir: 'dist',
    format: 'amd'
  }
}

6. 多入口打包

export default {
  // input: ['src/index.js', 'src/album.js'],
  input: {
    foo: 'src/index.js',
    bar: 'src/album.js'
  },
  output: {
    dir: 'dist',
    format: 'amd'
  }
}

7. 总结

优点:

  • 输出结果更加扁平
  • 自动移除未引用代码
  • 打包结果依然完全可读

缺点:

  • 加载非ESM的第三方模块比较复杂
  • 模块最终都被打包到一个函数中,无法实现HMR
  • 浏览器环境中,代码拆分功能依赖AMD

如果我们正在开发应用程序,建议使用webpack

如果开发一个框架或者类库,可以选择Rollup

相关文章

网友评论

    本文标题:Rollup

    本文链接:https://www.haomeiwen.com/subject/orklultx.html