我这里是写了一个vue轮播图插件,所以我使用了vue的脚手架工具建立一个项目,固然你也能够选择本身搭建脚手架。javascript
本例中我会使用vue脚手架建立一个项目,并发布到npm上面去。html
全局安装vue
首先,要建立项目,封装vue的插件用webpack-simple很合适,所以你须要全局安装@vue/cli-init
插件:java
yarn global add @vue/cli-init
//或者
npm install @vue/cli-init -g
复制代码
使用vue init webpack-simple vue-test-plugin
初始化目录; vue-test-plugin
是项目名称,也是新建项目的目录。 而后我使用全局安装失败了,那么我就使用局部安装把。node
局部安装webpack
新建D:/test
test文件夹,局部安装@vue/cli-init
插件:git
yarn add @vue/cli-init
//或者
npm install @vue/cli-init
复制代码
安装成功以后,使用命令初始化vue-test-plugin
项目:github
./node_modules/.bin/vue init webpack-simple vue-test-plugin
复制代码
而后就一路enter
直到项目建立完成。建立完成后的目录以下:web
在./src/
目录下实现你本身的功能,个人功能实现完了以后以下:npm
./src/lib/banner.vue
:是主功能文件
./src/lib/index.js
:
import VueBanner from './banner.vue'
const plugin = {
install: function(Vue) {
Vue.component(VueBanner.name, VueBanner)
}
}
// 这里的判断很重要
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(plugin)
}
export default plugin
复制代码
咱们在webpack配置的入口文件就是index.js,install是挂载组件的方法,有了它咱们就能够在外部use一个插件了。
若是外部使用<script>
引入的话window
存在,window.Vue.use(plugin)
就直接将插件挂在在全局了。
package.json 文件
{
"name": "vue-test-plugin",
"description": "vue的插件测试",
"version": "1.0.1",
"author": "姓名 <xxx@xxx.com>",
// 配置main结点,若是不配置,咱们在其余项目中就不用import XX from '包名'来引用了,只能以包名做为起点来指定相对的路径
"main":"dist/vue-test-plugin.js",
//开源协议
"license": "MIT",
// 由于组件包是公用的,因此private为false
"private": false,
"scripts": {
"dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot",
"build": "cross-env NODE_ENV=production webpack --progress --hide-modules"
},
// 指定代码所在的仓库地址
"repository": {
"type": "git",
"url": "git+xxxxx" //这里写github的git地址,格式为:'git+' + gitHubURL
},
"dependencies": {
"vue": "^2.5.11"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
],
// 指定关键字
"keywords": [
"vue",
"test-plugin"
],
// 项目官网的url
"homepage": "github地址下的readme.md文件地址",
"devDependencies": {
...
}
}
复制代码
webpack.config.js 文件
// entry: './src/main.js',
entry: './src/lib/index.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
// filename: 'build.js'
filename: '/vue-test-plugin.js',
library: 'VueTestPlugin',
libraryTarget: 'umd',
umdNamedDefine: true
},
复制代码
因为不是全部使用组件的人都是经过 npm 安装使用 import 引入组件的,还有不少人是经过 <script>
标签的方式直接引入的,因此咱们要将 libraryTarget 改成 umd 格式,同时咱们要配置文件入口和出。
.gitignore 文件
dist/ //删除此行
复制代码
由于要用dist文件夹,因此在.gitignore文件中把dist/
去掉。
index.html 文件
<!-- <script src="/dist/build.js"></script> -->
<script src="/dist/vue-test-plugin.js"></script>
复制代码
yarn build
//或者
npm run build
复制代码
由于在import的时候,自动会加载packge.json
文件中的main
中的路径,我这里是:dist/vue-test-plugin.js
,所以会去读取这个文件,因此须要打包。
vue-test-plugin
根目录下,添加npm帐号:npm adduser
npm publish
若是发布过程当中出现此问题是由于使用了淘宝镜像,须要切换成原来的镜像,发布成功后,再切回来。
检查是否使用了淘宝镜像
npm config get registry
复制代码
出现以下结果:
若是出现如上结果,继续下一步
切换成原来的npm源
npm config set registry=http://registry.npmjs.org
复制代码
继续npm publish
发布npm包。
切回淘宝镜像
npm config set registry=https://registry.npm.taobao.org/
复制代码