前言
最近做項目,發現有很多可抽離出來的元件,以前開發元件是用gulp和webpack搭建的腳手架,需要配置一堆
loader
之類的東西,配置完成後,編譯出來的代碼不僅可讀性差,而且代碼體積偏大。是以想找尋新的編譯工具,最後發現
vue.js
,
react.js
等流行庫都用了
rollup.js
來編譯代碼,而且
rollup.js
可以編譯輸出各種子產品規範的代碼
AMD、Commonjs、UMD、IIFE
。是以也入門
rollup.js
。
rollup介紹
官方描述
Rollup 是一個 JavaScript 子產品打包器,可以将小塊代碼編譯成大塊複雜的代碼,例如 library 或應用程式。Rollup 對代碼子產品使用新的标準化格式,這些标準都包含在 JavaScript 的 ES6 版本中,而不是以前的特殊解決方案,如 CommonJS 和 AMD。ES6 子產品可以使你自由、無縫地使用你最喜愛的 library 中那些最有用獨立函數,而你的項目不必攜帶其他未使用的代碼。ES6 子產品最終還是要由浏覽器原生實作,但目前 Rollup 可以使你提前體驗。rollupjs官網
1、配置檔案
1、安裝對應的包
// rollup編譯的核心子產品
npm install rollup -D
// rollup的ES6編譯插件
npm install rollup-plugin-babel -D
// 一堆編譯的loader
npm install -D @babel/cli @babel/core @babel/node @babel/plugin-transform-react-jsx @babel/preset-env @babel/preset-react @babel/runtime @babel/plugin-external-helpers @babel/plugin-proposal-object-rest-spread @babel/plugin-syntax-object-rest-spread
// plugin插件
npm install -D rollup-plugin-commonjs rollup-plugin-node-resolve rollup-plugin-serve rollup-plugin-uglify rollup-plugin-livereload rollup-plugin-postcss
2、檔案目錄
.
├── build // 編譯打包後的檔案夾
│ ├── css
│ │ └── index.css // css
│ ├── img // 圖檔無法自動打包過去
│ │ ├── plusRightsTab.png
│ │ └── qiy-icon_1.png
│ └── js
│ └── index.js
├── config
│ ├── build.js
│ ├── compile_task.js // 編譯檔案
│ ├── dev.js
│ ├── rollup.config.dev.js // 開發環境配置檔案
│ ├── rollup.config.js // 公用配置檔案
│ └── rollup.config.prod.js // 生産環境配置檔案
├── index.html 入口html
├── package-lock.json
├── package.json
├── postcss.config.js // 移動端将px轉換為rem的配置檔案
└── src
├── img
│ ├── plusRightsTab.png
│ └── qiy-icon_1.png
├── js
│ └── index.js
└── sass
├── _init.scss
├── _mixin.scss
└── tabs.scss
2、rollup配置
1、編譯配置檔案
rollup.config.js
/**
* Created by wangjia16 on 2019/8/12.
*/
const ENV = process.env.NODE_ENV;
const path = require('path');
const babel = require('rollup-plugin-babel');
const buble = require('rollup-plugin-buble');
const json = require('rollup-plugin-json');
// 編譯npm子產品及其全局變量子產品 插件子產品
const nodeResolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const nodeGlobals = require('rollup-plugin-node-globals');
//開啟服務插件
const serve = require('rollup-plugin-serve');
//編譯css
const postcss = require('rollup-plugin-postcss');
const sass = require('node-sass');
// 處理rem換算
// const pxtorem = require('postcss-pxtorem');
const px2rem = require('postcss-px2rem');
const image = require('rollup-plugin-img');
// 監聽檔案改變,并重新整理浏覽器
const livereload = require('rollup-plugin-livereload');
const resolveFile = function (filePath) {
return path.join(__dirname, '..', filePath)
};
const resoleFileName = function (filePath) {
let imgPath = '../build';
return path.join(__dirname, imgPath, filePath)
};
const isProductionEnv = ENV === 'production';
const processSass = function(context, payload) {
return new Promise(( resolve, reject ) => {
sass.render({
file: context
}, function(err, result) {
console.log(result);
if( !err ) {
resolve(result);
} else {
console.log(err);
reject(err)
}
});
})
};
module.exports = [
{
input: resolveFile('src/js/index.js'),
output: {
file: resolveFile(`build/js/index.js`),
// format: 'cjs',
format: 'umd',
name: 'panTabs',
},
plugins: [
postcss({
extract: './build/css/index.css',
// extract: true,
minimize: isProductionEnv,
extensions:['css','scss'],
process:processSass,
}),
json(),
babel({
exclude: '**/node_modules/**'
}),
buble(),
nodeResolve({
// module: true, // ES6子產品盡可能使用 ‘module’字段
}),
commonjs({
include: [
'node_modules/**'
],
exclude: [
'node_modules/process-es6/**'
],
namedExports: {
'node_modules/react/index.js': ['Component', 'PureComponent', 'Fragment', 'Children', 'createElement']
}
}),
nodeGlobals(),
// 開啟服務
ENV == 'development' ?
serve({
open: true, // 是否打開浏覽器
contentBase: './', // 入口html的檔案位置
historyApiFallback: true, // Set to true to return index.html instead of 404
host: 'localhost',
port: 3003
})
: '',
livereload()
],
},
];
注意:如果是umd,需要注意的是umd格式必須指定子產品的名稱,通過name屬性來實作
2、編譯
rollup.config.dev.js
檔案
process.env.NODE_ENV = 'development';
const configList = require('./rollup.config');
configList.map((config, index) => {
config.output.sourcemap = true;
return config;
});
module.exports = configList;
3、編譯
rollup.config.prod.js
檔案
process.env.NODE_ENV = 'production';
const { uglify } = require('rollup-plugin-uglify');
const configList = require('./rollup.config');
configList.map((config, index) => {
config.output.sourcemap = false;
config.plugins = [
...config.plugins,
...[
uglify()
]
];
return config;
});
module.exports = configList;
4、
.babelrc
檔案配置
{
"presets": [
"@babel/preset-react",
[
"@babel/preset-env",
{
"modules": false
}
]
],
"plugins": [
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-syntax-object-rest-spread",
"@babel/plugin-transform-react-jsx",
[
"@babel/plugin-transform-runtime",
{
"absoluteRuntime": false,
"corejs": false,
"helpers": false,
"regenerator": false,
"useESModules": false
}
]
]
}
5、在
package.json
裡配置執行腳本
"dev": "node ./config/dev.js",
"build": "node ./config/build.js"
執行腳本,編譯
1、執行腳本後,會自動啟動浏覽器
- 在項目中執行
,編譯結果在目錄npm run dev
build/index.js
- 編譯結果為
常見錯誤
1、編譯
react
時,
plugins
位置放置不對,會導緻文法錯誤
plugins: [
// 原先的位置,放在這裡會導緻文法錯誤
// nodeResolve(),
// commonjs(),
// nodeGlobals(),
postcss({
extract: true,
minimize: isProductionEnv,
extensions:['css','scss'],
process:processSass
}),
json(),
babel({
exclude: '**/node_modules/**'
}),
buble(),
nodeResolve(),
commonjs(),
nodeGlobals(),
]
2、編譯react,還會出現的錯誤
意思是說 React目前沒有真正提供ES子產品,是以需要在配置中解決這一問題
解決方案是在插件commonjs裡進行配置
配置如下
commonjs({
include: [
'node_modules/**'
],
exclude: [
'node_modules/process-es6/**'
],
namedExports: {
'node_modules/react/index.js': ['Component', 'PureComponent', 'Fragment', 'Children', 'createElement']
}
}),
總結
本文簡單介紹了rollupjs針對js,sass所做的編譯處理,記錄在此,一是分享給需要的同學使用,二是友善自己後續回看。
使用場景
- 想要快速配置開發元件
- 要用ES6+文法開發
- 代碼清潔,清理無用代碼(tree-shaking)
參考資料:
- rollup官網:rolluojs.com
- rollupjs實戰學習筆記