一、创建项目
vue create add-ui
default (babel, eslint)
> Manually select features
? Check the features needed for your project:
(*) Babel
( ) TypeScript
( ) Progressive Web App (PWA) Support
(*) Router
>(*) Vuex
(*) CSS Pre-processors
( ) Linter / Formatter
( ) Unit Testing
( ) E2E Testing
二、创建测试组件
将文件夹src修改为examples,然后在根目录新增文件夹packages
test.vue:
<template>
<div>
<h3>{{name}}</h3>
<div class="num">{{ count }}</div>
<button @click="increment">自增</button>
</div>
</template>
<script>
export default {
name: 'test',
props: {
name: String,
default: ''
},
data() {
return {
count: 0
};
},
methods: {
increment() {
this.count++;
}
}
};
</script>
packages/test/index.js:
import test from './src/test';
export default Vue => {
Vue.component(test.name, test);
};
package/index.js:
import test from './test';
const components = [test];
const install = function(Vue) {
if (install.installed) return;
components.map(component => {
Vue.use(component);
});
};
// 全局引用可自动安装
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue);
}
export default {
install,
test
};
export { test };
三、根目录新增vue.config.js
const path = require('path')
module.exports = {
// 修改默认的入口
pages: {
index: {
entry: 'examples/main.js',
template: 'public/index.html',
filename: 'index.html'
}
},
chainWebpack: config => {
// vue默认@指向src目录,这里要修正为examples,另外新增一个~指向packages
config.resolve.alias
.set('@', path.resolve('examples'))
.set('~', path.resolve('packages'));
// lib目录是组件库最终打包好存放的地方,不需要eslint检查
// examples/docs是存放md文档的地方,也不需要eslint检查
config.module
.rule('eslint')
.exclude.add(path.resolve('lib'))
.end()
.exclude.add(path.resolve('examples/docs'))
.end();
// packages和examples目录需要加入编译
config.module
.rule('js')
.include.add(/packages/)
.end()
.include.add(/examples/)
.end()
.use('babel')
.loader('babel-loader')
.tap(options => {
// 修改它的选项...
return options;
});
}
};
四、修改package.json
// npm输出的文件
"main": "lib/add-ui.common.js",
"author": "df",
// 新增命令
scripts: {
"lib": "vue-cli-service build --target lib --name add-ui --dest lib packages/index.js"
}
然后将"private"改为 false,否则会报错如下:
五、新增.npmignore,添加好忽略文件,打包发布
npm run lib//打包
npm publish//发布
tip : 发布之前需要登录
//切换源
npm set registry http://192.168.2.xxx:xxxx
//添加用户
npm adduser --registry http://192.168.2.xxx:xxxx
//登录
npm login
六、使用
在需要使用的vue项目中npm install add-ui
添加进来,然后在main.js中进行全局注册,如下:
import addUI from 'add-ui'
Vue.use(addUI);
然后在需要使用的页面直接进行使用,如下:
效果:
使用的名称(即为test)