前置步骤:
使用 vue-cli 3 创建项目。
1. 删除 public 文件夹
2. 清空 src 文件夹
3. 在 src 中创建入口文件 main.js
4. 在 src 中创建组件文件夹 components
得到以下结构
第一步:在 src/components 中 创建组件(以简单的 TButton 按钮组件为例)
<template>
<button class="t-button"
:class="{'t-button--disabled':disabled}"
@click="onButtonClick">
<slot></slot>
</button>
</template>
<script>
export default {
name: "TButton",
props: { disabled: Boolean },
methods: {
onButtonClick(e) {
if (this.disabled) return;
this.$emit("click", e);
}
}
};
</script>
<style>
.t-button {
padding: 5px 10px;
color: #ffffff;
background-color: #c20c0c;
}
.t-button--disabled {
color: #909399;
background: rgba(0, 0, 0, 0.12);
}
</style>
第二步:编写入口文件 main.js
import TButton from './components/TButton.vue'
const components = [TButton]
/**
* 绑定组件
* @param Vue
*/
function bindComponents(Vue) {
components.forEach(component => {
Vue.component(component.name, component)
})
}
/**
* 为了使用 Vue.use() 使用插件
* https://cn.vuejs.org/v2/api/#Vue-use
* @param Vue
*/
function install(Vue) {
bindComponents(Vue)
}
export default { install, TButton }
第三步:配置打包脚本
进入 package.json,将 build 脚本改为
vue-cli-service build --target lib --dest lib ./src/main.js
--target lib 使用库模式打包
--dest lib 输出路径 lib 文件夹
./src/main.js 入口
执行打包脚本
npm run build 或 yarn build
第四步:编写 package.json
{
"name": "npm-test-ljw1412",
"version": "0.1.0",
"author": "ljw1412",
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build --target lib --dest lib ./src/main.js",
"lint": "vue-cli-service lint"
},
"main": "lib/npm-test-ljw1412.common.js",
"files": [
"lib",
"src"
],
...
}
name: 包的名称,要上传 npm 的最好搜一下有没有重名的,或者使用命名空间。
main: 指定了加载的入口文件,require 或 import 就会加载这个文件。
files: 被项目包含的文件名数组
第五步: 上传 npm
1. 检查自己是否使用了其他npm镜像。(如果是,请切换回官方。否则可能会出现权限不足的问题)
2. 在 npm 注册账号(如果有跳过)
3. 在项目根文件夹执行 npm login 按提示输入用户名,密码,email
出现 "Logged in as * on https://registry.npmjs.org/."即登陆成功。
4. 执行 npm publish 进行上传
5. 如果想撤回版本 npm unpublish 包名[@版本]
下图为上传成功的结果图。
第六步:使用
在你的开发项目中导入包
yarn add npm-test-ljw1412
在项目入口文件 main.js 中
import npmTest from 'npm-test-ljw1412'
import 'npm-test-ljw1412/lib/npm-test-ljw1412.css'
Vue.use(npmTest)
直接在 vue 页面中使用组件
<t-button>测试</t-button>
<t-button disabled>测试</t-button>
效果图: