親測好用,如出錯,請留言
1.項目初始化
使用vue腳手架創建,但vuecli太重,我們使用簡單的工程腳手架進行處理,輸入命令
vue init webpack-simple my-project
npm install
npm run dev
初始化以后看一下目錄:

2. src中寫入vue組件

結構類似於這樣
考慮其他ui組件的使用,比如vant,
import vant from ‘vant’
Vue.use(vant)
等
index.js中代碼可以這樣寫:
import decreaseFun from './decrease-function.vue'
sumFunction.install = (Vue) =>{
Vue.component(decreaseFun.name,decreaseFun)
}
export default decreaseFun
而在vue組件中
<template>
<div class="calculate">
<p>{{a}}-{{b}}={{sum}}</p>
</div>
</template>
<script>
export default {
name: "decreaseFunc",
props: ["num3", "num4"],
data() {
return {
a: this.num3 ? this.num3 : 0,
b: this.num4 ? this.num4 : 0,
sum: 0
};
},
mounted() {
this.sumFunc();
},
methods: {
}
};
</script>
<style>
.calculate {
width: 100%;
line-height: 26px;
}
</style>
和正常寫法一樣
3.修改webpack.config.js
因為我們最終輸出的是build以后的文件內容,需要配置調整
entry: NODE_ENV == 'development' ? './src/main.js' : './src/myPlugin/decreaseFunction/index.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'decreaseFunction.js',
library: 'decreaseFunction', // 指定的就是你使用require時的模塊名
libraryTarget: 'umd', // 指定輸出格式
umdNamedDefine: true // 會對 UMD 的構建過程中的 AMD 模塊進行命名。否則就使用匿名的 define
},
4.修改package.json
添加或者修改
"main": "dist/decreaseFunction.js"
"private": false //也可以改為true
5 輸入命令
npm run build
6 npm發布
1.首先去npm官網注冊賬號
2.在該項目根目錄下啟用cmd
3.輸入命令 npm login
4.報錯,原因可能是因為你需要驗證郵箱,或者npm包重名
5.npm publish 成功
7 使用
npm install xxx --save
import myplugin from 'xxx'
Vue.use(myPlugin)
