Open iambigchen opened 4 years ago
之前的引入方式,是examples/src/main.js中,直接引入我们的ui库。这样的引入方式,是属于全部引入,如果我们不想全部引入,只是使用了该库的个别组件,那我们就需要按需引入的方式了。
按需引入的方法和element-ui一样,需要配合一个babel-plugin-component
使用。
babel-plugin-component
原理是
import { Button } from 'components'
to
var button = require('components/lib/button')
require('components/lib/button/style.css')
这里也就能看出来之前我们helloworld
组件的目录为什么要那么设置了
配置我们examples下的babel-plugin-component
插件
examples/.babelrc
{ ... "plugins": ["transform-vue-jsx", "transform-runtime", [ "component", { "libraryName": "element-cy", "style": true, "styleLibrary": { "name": "theme-chalk/lib/", // same with styleLibraryName "path": "[module].css", // the style path. e.g. module Alert => alert/index.css }, "libDir": "src/components" } ]] .... }
这里的配置和element-ui有些不同,因为我们修改了目录结构,所以路径指定也不同了
配置完插件后,就修改我们的main.js,使用按需引入的方式引入
>examples/src/main.js
```js
...
import {helloworld} from 'element-cy'
Vue.use(helloworld)
...
尝试着自己实现elementUI
需求分析
之前用elementUI写过很多的项目,只是单纯的拿来用。但是却没有想过是如何实现的,所以打算通过参照着官网的源码,从无到有的自己实现一下elementUI的部分功能。本文纯粹只是自己学习和个人总结使用
项目目录解析
本文用的是
webpack
进行代码打包,src
目录下放的是核心源码,examples
下是用vue-cli2构建的一个vue项目。打包后的文件放在lib
文件夹下, 所以package.json
中的main
指向了lib/index.js
。项目搭建
npm init
初始化一个npm
项目lib
文件夹里。并且配置了babel-loader
和vue-loader
,VueLoaderPlugin
vue-cli2
脚手架新起一个项目。HelloWorld
1.在src/components下新建一个helloworld文件夹,在该文件夹下,新建index.js和src文件夹。index.js作为这个组件的入口文件,而src里面放的才是该组件的主要实现代码
// 为该组件添加一个install方法,用于vue extend helloworld.install = function(Vue, options) { // 将该组件挂载到vue的全局组件中 Vue.component(helloworld.name, helloworld) } export default header
这里这样的目录结构,主要是为了按需引入所准备的。后面有会说明这样写的好处
编写入口文件index.js
const components = [ helloworld ]
const install = function(Vue, options) { components.forEach(component => { Vue.component(component.name, component) }) }
export default { version: 1.0, install }
这时起动examples的服务,在浏览器查看效果,发现我们的helloworld组件已经生效了