zl-democs1
v1.0.0
Published
## Project setup ``` npm install ```
Downloads
1
Readme
zl_dev
Project setup
npm install
Compiles and hot-reloads for development
npm run serve
Compiles and minifies for production
npm run build
打包组件
npm run lib
Lints and fixes files
npm run lint
Customize configuration
介绍
- App.vue为开发入口,
- main.js是开发时候的配置
- packages目录是组件目录,我们开发的组件就存放在这里
需求
- 采用npm组件的方式打包vue文件成js,然后直接引入的方式用于项目使用,而不是通过npm安装的方式
实现
- 利用脚手架创建项目 vue create demo
- 创建好之后在目录新建一个packages目录用于存放组件,当然也可以在src中创建一个目录存放
- 由于创建了packages目录在src外部,脚手架不会对该目录编译,因此需要配置webpack进行编译,在vue.config.js文件中配置
// vue.config.js
module.exports = {
pages: {
index: {
entry: 'src/main.js',
template: 'public/index.html',
filename: 'index.html'
}
},
chainWebpack: config => {
config.module
.rule('js')
.include
.add('/packages')
.end()
.use('babel')
.loader('babel-loader')
.tap(options => {
return options
})
}
}
- 创建组件目录和组件入口,先在packages目录下创建一个zlDemo文件和一个index.js文件,用来配置该目录下的组件
// packages/index.js
import zlDemo from './zlDemo'
// 存储组件列表
const components = [
zlDemo
]
// 定义 install 方法,接收 Vue 作为参数。如果使用 use 注册插件,则所有的组件都将被注册
const install = function (Vue) {
// 判断是否安装
if (install.installed) return
// 遍历注册全局组件
components.map(component => Vue.component(component.name, component))
}
// 判断是否是直接引入文件
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue)
}
export default {
// 导出的对象必须具有 install,才能被 Vue.use() 方法安装
install,
// 以下是具体的组件列表
zlDemo
}
- 创建组件,在packages/zlDemo目录下创建index.js和index.vue组件文件,代码如下
// packages/zlDemo/index.js
import zlToast from './index.vue'
zlToast.install = function (Vue) {
Vue.component(zlToast.name, zlToast)
}
export default zlToast
// packages/zlDemo/index.vue
<template>
<div class="zl-demo ceshi">
这是一个demo
</div>
</template>
<script>
export default {
name: 'zlDemo'
}
</script>
<style>
</style>
- 配置打包命令,在package.json文件中添加lib命令用于打包
// package.json
"scripts": { // 配置打包命令
"lib": "vue-cli-service build --target lib --name zlDemo1 --dest lib packages/index.js"
}
"name": "zlDemo", // 组件名称
"version": "0.1.0", // 版本号