1.fork elementUI
2.精簡代碼 (代碼地址 https://github.com/yklhello/basic-element.git)
3.剖析結構
基礎剖析
(1) ElementUI按需引入和全量引入原理
全量:
import ElementUI from 'element-ui'
Vue.use(ElementUI)
核心代碼
src/index.js
/* Automatically generated by './build/bin/build-entry.js' */ import EncounterFilter from '../packages/encounterFilter/index.js' import Footer from '../packages/footer/index.js' const components = [ EncounterFilter, Footer ] const install = function (Vue, opts = {}) { components.forEach(component => { Vue.component(component.name, component) }) } /* istanbul ignore if */
if (typeof window !== 'undefined' && window.Vue) { install(window.Vue) } export default { version: '0.0.3', install, EncounterFilter, Footer }
項目中使用 Vue.use() 會調用插件的install方法,如上Vue.use(ElementUI)會自動在全局注冊所有組件
按需:
import { Select } from 'element-ui'
Vue.use(Select)
核心代碼
packages/xxx/index.js
import Select from './src/Select' Select.install = function (Vue) { Vue.component(Select.name, Select) } export default Select
Vue.use(Select) 同樣會調用install方法,注冊當前組件,避免包過大
(2) 按需引入和全量引入的打包方式區別
全量引入
build/webpack.common.js 將elementUi打包成一個element-ui.common.js文件
module.exports = { entry: { app: ['./src/index.js'] }, output: { ‘
path: path.resolve(process.cwd(), './lib'),
publicPath: '/dist/',
filename: 'element-ui.common.js', // 輸出文件名稱
chunkFilename: '[id].js',
libraryTarget: 'commonjs2'
}
...
}
libraryTarget:“commonjs”,在export對象上定義library設置的變量。在node中支持,瀏覽器中不支持。
libraryTarget:“commonjs2”,直接用module.export導出export,會忽略library設置的變量。在node中支持,在瀏覽器中不支持。 開發中可以 import ElementUI from 'element-ui'
libraryTarget:“amd”,在define方法上定義library設置的變量,不能用script直接引用,必須通過第三方模塊RequireJS來時用
libraryTarget:“umd”,該方案支持commonjs、commonjs2、amd,可以在瀏覽器、node中通用。
常用 commonjs2,umd
按需引入,多文件入口,將elementUI分組件打包
const Components = require('../components.json');
const webpackConfig = { entry: Components, output: { path: path.resolve(process.cwd(), './lib'), publicPath: '/dist/', filename: '[name].js', chunkFilename: '[id].js', libraryTarget: 'commonjs2' }, ... }
下一章介紹elementUI樣式文件打包方式