按需加載的原理
按需加載,本質上是把一個組件庫的不同組件 拆分成不同文件 ,按照需要引用對應的文件,而該文件暴露一個 install方法 ,供Vue.use使用。 比如:我只想引用element庫里的一個Button組件
import Button from 'element-ui/lib/Button.js'import Button from 'element-ui/lib/theme-chalk/Button.css'Vue.use(Button);
上面的寫法比較繁瑣,而且需要知道每個組件的實際路徑,使用起來并不方便,所以我們還需要借助一個轉換插件。
先來看看 element 是怎么做的,官方的的「快速手上」:

element使用一個了babel插件,作用就是代碼轉換:
import { Button } from 'components'// 轉換為var button = require('components/lib/button')require('components/lib/button/style.css')到這我們可以知道,要搭建一個按需加載的組件庫。 主要工作 需要兩點:
組件代碼的編寫規(guī)范
我們在項目的跟目錄建一個文件夾packages,下面放我們的組件:

packages下每一個文件夾對應一個組件所需要的資源,在index.js定義組件的install方法。而packages/index.js存放了在全量加載時用的install方法
packages/Button/index.js:
import Button from './src/main';Button.install = function(Vue) { Vue.component(Button.name, Button);};export default Button;packages/Button/src/main.vue:
<template> <div> 我是一個Button組件 </div></template>
packages/index.js:
import Button from './Button';import Loading from './Loading';import LoadMore from './LoadMore';const components = [ Button, LoadMore, Loading];const install = function(Vue) { components.forEach(component => { Vue.component(component.name, component); });}if (typeof window !== 'undefined' && window.Vue) { install(window.Vue)}export default { install, // 全量引入 Button, LoadMore, Loading};webpack配置
組件代碼寫好了,接下來需要配置一下webpack的打包邏輯。我們復用vue-cli生成的模板,在上面做一些必要更改:
多入口
每個組件獨立生成一個對應的js和css,這就需要我們在入口處就把組件的引用定義好:
webpack.prod.conf.js:
const entrys = { Button: path.resolve(__dirname, '../packages/Button'), index: path.resolve(__dirname, '../packages')};const webpackConfig = merge(baseWebpackConfig, { entry: entrys, // ......});上述配置每增加一個組件都需要修改entrys,我們可以優(yōu)化一下,使其 動態(tài)生成 :
webpack.prod.conf.js:
const entrys = require(./getComponents.js)([組件目錄入口]);const webpackConfig = merge(baseWebpackConfig, { entry: entrys, ......});getComponents.js:
const fs = require('fs');const path = require('path');/** * 判斷剛路徑是否含有index.js * @param {String} dir */function hasIndexJs(dir) { let dirs = []; try { dirs = fs.readdirSync(dir); } catch(e) { dirs = null; } return dirs && dirs.includes('index.js');}/** * 獲取指定入口和入口下包含index.js的文件夾的路徑 * @param {String} entryDir */const getPath = function(entryDir) { let dirs = fs.readdirSync(entryDir); const result = { index: entryDir }; dirs = dirs.filter(dir => { return hasIndexJs(path.resolve(entryDir, dir)); }).forEach(dir => { result[dir] = path.resolve(entryDir, dir); }); return result;}module.exports = getPath;修改webpack的輸出
默認生成的js文件并不支持ES6引入,在這里我們設置成 umd
output: { path: config.build.assetsRoot, filename: utils.assetsPath('[name].js'), library: 'LoadOnDemand', libraryTarget: 'umd'},配置 babel-plugin-component -D
上面的組件庫打包發(fā)布到npm上之后。我們在使用的時候npm install babel-plugin-component -D之后,修改一下.babelrc.js:
"plugins": [ [ "component", { "libraryName": "load-on-demand", // 組件庫的名字 "camel2Dash": false, // 是否把駝峰轉換成xx-xx的寫法 "styleLibrary": { "base": false, // 是否每個組件都默認引用base.css "name": "theme" // css目錄的名字 } } ] ],這里提一下屬性 camel2Dash ,默認是開啟的,開啟狀態(tài)下假如你的組件名是vueCompoent,引用的css文件會變成vue-component.css。
結語
上面demo的代碼放在了個人github github.com/jmx16449196… 大家如果有更好的實現(xiàn)方法,或者我上面還有什么需要更正的錯誤,歡迎交流。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答