前置步驟:
使用 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>
效果圖: