esModule 打包器
- cpnm i rollup
- rollup ./src/index.js --format iife --file dist/bound.js
- 配置文件 rollup.config.js
- rollup --conifg使用配置文件打包
- 自動開啟了tree-shaking,沒有用到的模塊不會打包
- 采用配置文件運行 npx rollup --config
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'iife'
}
}
插件
import json from 'rollup-plugin-json'
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'iife'
},
plugins: [
json()
]
}
第三方模塊
- rollup-plugin-node-resolve 來支持對第三方npm模塊,只能處理esModule模塊
import json from 'rollup-plugin-json'
import resolve from 'rollup-plugin-node-resolve'
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'iife'
},
plugins: [
json(),
resolve()
]
}
加載commonJs模塊
- rollup-plugin-commonjs 來支持commonJs模塊
import json from 'rollup-plugin-json'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'iife'
},
plugins: [
json(),
resolve(),
commonjs()
]
}
代碼拆分
- 使用es動態(tài)導(dǎo)入,rollup會自動分包, --format不能使用iife,因為這個模式是把所有模塊放到一個函數(shù)中,采用amd方式打包 ,同時配置輸出要采用dir文件夾輸出方式
import('./logger').then(({ log }) => {
log('code splitting~')
})
//config.js
export default {
input: 'src/index.js',
output: {
// file: 'dist/bundle.js',
// format: 'iife'
dir: 'dist',
format: 'amd'
}
}
多入口打包
- amd方式打包的文件頁面需要用require.js去解析,通過script data-main指定入口文件
export default {
// input: ['src/index.js', 'src/album.js'],
input: {
foo: 'src/index.js',
bar: 'src/album.js'
},
output: {
dir: 'dist',
format: 'amd'
}
}
對比webpack
- 優(yōu)點
- 輸出結(jié)果更扁平
- 自動移除未引用代碼
- 打包結(jié)果可讀
- 缺點
- 加載非es第三方模塊復(fù)雜
- 模塊最終打包到一個函數(shù),無法實現(xiàn)HMR模塊熱替換
- 瀏覽器環(huán)境代碼拆分依賴AMD庫(require.js)
開發(fā)應(yīng)用采用webpack
開發(fā)js框架或者庫 采用rollup
parcel
- 零配置打包器
- 支持熱替換
- 自動安裝依賴
- 支持動態(tài)導(dǎo)入拆分代碼
- cnpm i parcel-bundler
- npx parcel src/*.html 進(jìn)行開發(fā)環(huán)境運行
- npx parcel build src/*.html 生成環(huán)境打包
if (module.hot) {
module.hot.accept(() => {
console.log('hmr')
})
}