一、功能簡介
Rollup 是一個 JavaScript 模塊打包器,可以把小塊代碼編譯成大塊複雜的代碼,它特別適合於 ES6 模塊化的打包。與其他模塊打包工具不同,它使用的是ES6的標準語法進行打包。生成的代碼可讀性高,並且體積小,可以有效地減少代碼的載入時間,提升性能。
二、基本使用
1、全局安裝rollup
$ npm install -g rollup
2、新建main.js和foo.js兩個 JavaScript文件,main.js使用ES6模塊導入foo.js文件
// main.js
import foo from './foo.js';
console.log(foo());
// foo.js
export default function () {
return 'hello world!';
}
3、使用rollup進行打包
$rollup main.js --file bundle.js --format iife
參數說明:
–file – 指定打包後生成的文件名
–format – 指定生成代碼的格式,我這裡指定了iife。iife即一個自動執行的函數,這樣就可以在頁面中使用打包後的代碼,而不需要擔心變數污染問題
三、高級使用
1.Rollup插件
Rollup 有很多插件,可以幫助我們完成一些高級的功能。
1)、rollup-plugin-babel: 將ES6及以上版本的JavaScript代碼轉成ES5版本
$npm install --save-dev rollup-plugin-babel@latest
配置方式:
// rollup.config.js
import babel from 'rollup-plugin-babel';
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'cjs'
},
plugins: [
babel({
exclude: 'node_modules/**' // 排除node_modules下的文件
})
]
};
2)、rollup-plugin-commonjs: 將CommonJS模塊轉成ES6模塊
$npm install --save-dev rollup-plugin-commonjs@latest
配置方式:
// rollup.config.js
import commonjs from 'rollup-plugin-commonjs';
export default [{
input: 'src/index.js',
output: {
file: 'dist/bundle-cjs.js',
format: 'cjs',
exports: 'named'
},
plugins: [
commonjs({
include: /node_modules/
})
]
}];
3)、rollup-plugin-node-resolve: 解析導入模塊
$npm install --save-dev rollup-plugin-node-resolve@latest
配置方式:
// rollup.config.js
import resolve from 'rollup-plugin-node-resolve';
export default [{
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'es'
},
plugins: [
resolve({
jsnext: true,
main: true,
browser: true
})
]
}];
2.Rollup配置文件
當打包的模塊較多,或者需要引入多個插件時,可以使用配置文件,將常用配置放到配置文件中,方便代碼的維護。
// rollup.config.js
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import resolve from 'rollup-plugin-node-resolve';
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'cjs'
},
plugins: [
babel(), // 配置babel
commonjs(), // 配置CommonJS
resolve() // 配置模塊導入
],
external: [
'react',
'react-dom'
]
};
四、總結
通過本文的介紹,我們可以看到rollup是一個高效的 JavaScript模塊打包工具,它使用ES6作為標準,體積小,性能好。與其它打包工具比較,它的代碼更可讀性好,且生成的代碼量更少。
同時,我們還可以了解到一些高級功能,例如:插件的使用,配置文件的使用等等。
因此,在實際工作中,我們應該靈活地選擇不同的工具來完成我們的工作,並儘可能熟悉它們的使用方式,這樣才能使我們的代碼更優雅,更好維護。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/308764.html