Webpack 大而全,Rollup 小而美
选择基本原则是:应用开发使用 Webpack,类库或者框架开发使用 Rollup。
参考
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 立即执行函数
AMD, Asynchronous Module Definition 异步模块规范
用于像RequireJS这样的模块加载器
// 定义defie('module-01', [], function() {return {init(){console.log('hello')}}})// 引用define(function (require) {var demo = require('dist/index');demo.init()});
CJS, CommonJS规范
适用于 Node 和 Browserify/Webpack
通过 require 及 exports 进行导入导出 (进一步延伸的话,module.exports 属于 commonjs2)
UMD, Universal Module Definition 通用模块规范
通用模块定义, 以amd、cjs、iife为一体
(function (root, factory) {if (typeof define === 'function' && define.amd) {// AMDdefine(['jquery'], factory);} else if (typeof exports === 'object') {// CommonJSmodule.exports = factory(require('jquery'));} else {// 全局变量root.returnExports = factory(root.jQuery);}}(this, function ($) {// ...}));
ESM, es module
将软件包保存为 ES 模块文件,在现代浏览器中可以通过 <script type=module> 标签引入
system, SystemJS模块加载器
插件
rollup-plugin-commonjs
实践
mkdir useRollupyarn init -yyarn add rollup --devnpx rollup ./src/index.jsnpx rollup ./src/index.js --file ./dist/bundle.js// =======================添加配置文件===========================npx rollup --confignpx rollup --config rollup.config.js
配置文件
// rollup.config.jsexport default {input: 'src/index.js',output: {file: 'dist/bundle.js',format: 'cjs'}};
加载json
yarn add @rollup/plugin-json --dev// 添加插件import json from '@rollup/plugin-json'plugins: [json()]// index.js
加载NPM模块
yarn add @rollup/plugin-node-resolve --devyarn add lodash-es// rollup.config.jsimport resolve from '@rollup/plugin-node-resolve'plugins: [resolve()]// index.jsimport { camelCase } from 'lodash-es'console.log(camelCase('hello rollup'))
加载CommonJS 模块
yarn add @rollup/plugin-commonjs --dev// rollup.config.jsimport commonjs from '@rollup/plugin-commonjs'plugins: [commonjs()]// ./cjs-module.jsmodule.exports = {foo: 'bar'}// index.jsimport cjs from './cjs-module'console.log(cjs)
code spliting(代码拆分 )
// ./src/index.js// 动态导入的模块会自动分包import('./logger').then(({ log }) => {log('code splitting~')})// ./rollup.config.jsoutput: {dir: 'dist',}
