vue组件库开发(一) 按需加载实现方式


 

ElementUI的支持全局引用和按需加载
全局引用

import ElementUI from 'element-ui';

import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI); 

全局引用,实际项目使用中,首先Vue.use()会调用插件的install方法,之后会全局注册所有组件

 源码解析 /src/index.js 截取部分

/* Automatically generated by './build/bin/build-entry.js' */
 import Dialog from '../packages/dialog/index.js';
 
 import Menu from '../packages/menu/index.js';
 

const components = [
  Dialog,
  Menu
]

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,
  Dialog,
 Menu
}

按需引入

import { ElButton, ElSelect } from 'element-ui';

Vue.use(ElButton)

Vue.use(ElSelect)

packages/button/index.js

import Button from './src/button';

/* istanbul ignore next */
ElButton.install = function(Vue) {
  Vue.component(ElButton.name, ElButton);
};

export default ElButton;

Vue.use(ElButton)调用install方法 完成button组件的全局注册 

全局引用和按需加载打包配置

全局引用

build/webpack.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'
  }
}

按需加载

build/webpack.component.js

 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'
  }
 ...
}

多入口,每个组件一个js

涉及概念,webpack配置:详解webpack的out.libraryTarget属性

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM