流程:
-
使用vue-cli生成一个项目(这里用的2.X)
-
项目根目录下创建一个文件夹(paskages)放置编写代码
创建packages/components/Button/src/button.vue
<template> <div> <button :style="buttonBgc"> <slot></slot> </button> </div> </template> <script> export default { name: 'SkyButton', props: { bgc: { type: String, default: 'blue' } }, computed: { buttonBgc() { return { background: this.bgc } } } } </script> <style lang="scss"> button { display: inline-block; line-height: 1; white-space: nowrap; cursor: pointer; background: #fff; border: 1px solid #dcdfe6; color: #606266; text-align: center; box-sizing: border-box; outline: none; margin: 0; font-weight: 500; padding: 12px 20px; font-size: 14px; border-radius: 4px; } </style>
创建packages/components/Button/index
import SkyButton from './src/button' // 为了在引用时候可以单独引入它 SkyButton.install = function (Vue) { Vue.component(SkyButton.name, SkyButton) } export default SkyButton
创建packages/index (作为入口文件)
import SkyButton from './components/Button/index' const components = [SkyButton] const install = function (Vue) { components.forEach((component) => { Vue.component(component.name, component) }) } export { SkyButton } // 使用时候既可以单独引入 export default { install }
-
在src/main.js引用它,并在src/views页面引用测试
import { SkyButton } from '../packages/index' Vue.use(SkyButton)
-
无bug,就准备以下几步发布
a: pake.json配置:
"name": "test-sky", //包名称 "version": "0.1.1", // 版本号 "private": false, "main": "dist/sky.umd.min.js", // 向外暴漏出去的文件,以便外部使用import导入 "author": "sky", "keywords": ["sky","天空"], "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint", "lib": "vue-cli-service build --target lib --name sky -dest lib packages/index.js" }, // target: 默认为构建应用,改为 lib 即可启用构建库模式 // name: 输出文件名 // dest: 输出目录,默认为 dist,这里我们改为 lib // entry: 入口文件路径 // vue-cli-service build --target lib --name lib [entry]
运行npm run lib ,事实是并没有生成lib文件夹,还是dist文件夹。main的值就是取得这里生成的主文件
b:确保在npm源 (登录npm)npm config set registry https://registry.npmjs.org
c: 运行npm login登录npm账号。(填写邮箱时候不能用注册的邮箱,需要重新申请个)
d:npm publish
e:发布成功后就可以在npm后台看到了,然后就安装引用
// main.js 引用
// import testSky from "test-sky"
// Vue.use(testSky)
// views/xxx.vue 引用
import { SkyButton } from "test-sky"
Vue.use(SkyButton)
end:小demo ok