Webpack 大而全,Rollup 小而美
选择基本原则是:应用开发使用 Webpack,类库或者框架开发使用 Rollup。 [part3]Rollup - 图1参考
https://rollupjs.org/guide/zh/#%E6%A6%82%E8%BF%B0overview
https://chenshenhai.github.io/rollupjs-note/note/chapter02/02-03.html

模块化格式

IIFE, Imdiately Invoked Function Expression 立即执行函数

一个自动执行的功能,适合作为<script>标签。

AMD, Asynchronous Module Definition 异步模块规范

用于像RequireJS这样的模块加载器

  1. // 定义
  2. defie('module-01', [], function() {
  3. return {
  4. init(){
  5. console.log('hello')
  6. }
  7. }
  8. })
  9. // 引用
  10. define(function (require) {
  11. var demo = require('dist/index');
  12. demo.init()
  13. });

CJS, CommonJS规范

适用于 Node 和 Browserify/Webpack
通过 requireexports 进行导入导出 (进一步延伸的话,module.exports 属于 commonjs2)

UMD, Universal Module Definition 通用模块规范

通用模块定义, 以amd、cjs、iife为一体

  1. (function (root, factory) {
  2. if (typeof define === 'function' && define.amd) {
  3. // AMD
  4. define(['jquery'], factory);
  5. } else if (typeof exports === 'object') {
  6. // CommonJS
  7. module.exports = factory(require('jquery'));
  8. } else {
  9. // 全局变量
  10. root.returnExports = factory(root.jQuery);
  11. }
  12. }(this, function ($) {
  13. // ...
  14. }));

ESM, es module

将软件包保存为 ES 模块文件,在现代浏览器中可以通过 <script type=module> 标签引入

system, SystemJS模块加载器

插件

rollup-plugin-commonjs

实践

  1. mkdir useRollup
  2. yarn init -y
  3. yarn add rollup --dev
  4. npx rollup ./src/index.js
  5. npx rollup ./src/index.js --file ./dist/bundle.js
  6. // =======================添加配置文件===========================
  7. npx rollup --config
  8. npx rollup --config rollup.config.js

配置文件

  1. // rollup.config.js
  2. export default {
  3. input: 'src/index.js',
  4. output: {
  5. file: 'dist/bundle.js',
  6. format: 'cjs'
  7. }
  8. };

插件是

加载json

  1. yarn add @rollup/plugin-json --dev
  2. // 添加插件
  3. import json from '@rollup/plugin-json'
  4. plugins: [
  5. json()
  6. ]
  7. // index.js

加载NPM模块

  1. yarn add @rollup/plugin-node-resolve --dev
  2. yarn add lodash-es
  3. // rollup.config.js
  4. import resolve from '@rollup/plugin-node-resolve'
  5. plugins: [
  6. resolve()
  7. ]
  8. // index.js
  9. import { camelCase } from 'lodash-es'
  10. console.log(camelCase('hello rollup'))

加载CommonJS 模块

  1. yarn add @rollup/plugin-commonjs --dev
  2. // rollup.config.js
  3. import commonjs from '@rollup/plugin-commonjs'
  4. plugins: [
  5. commonjs()
  6. ]
  7. // ./cjs-module.js
  8. module.exports = {
  9. foo: 'bar'
  10. }
  11. // index.js
  12. import cjs from './cjs-module'
  13. console.log(cjs)

code spliting(代码拆分 )

  1. // ./src/index.js
  2. // 动态导入的模块会自动分包
  3. import('./logger').then(({ log }) => {
  4. log('code splitting~')
  5. })
  6. // ./rollup.config.js
  7. output: {
  8. dir: 'dist',
  9. }