# 一、使用模板
使用[現成模板項目](https://gitee.com/cainiao_web/npm-publish-test.git),替換其中組件,install相關依賴。


# 二,重新搭建
## 1、創建項目
```
npm install -g @vue/cli 搭建工程
```
```
vue create llgtfoo-components-boxs 創建項目
```
## 2、在項目中添加組件庫文件夾
在根目錄下新建一個plugins文件夾,用來放組件,項目文件結構為:

## 3、修改vue.config.js文件
```
const path = require('path')
module.exports = {
// 修改 pages 入口
pages: {
index: {
entry: 'src/main.js', // 入口
template: 'public/index.html', // 模板
filename: 'index.html' // 輸出文件
}
},
// 擴展 webpack 配置
chainWebpack: config => {
// @ 默認指向 src 目錄
// 新增一個 ~ 指向 plugins
config.resolve.alias
.set('~', path.resolve('plugins'))
// 把 plugins 加入編譯,因為新增的文件默認是不被 webpack 處理的
config.module
.rule('js')
.include.add(/plugins/).end()
.use('babel')
.loader('babel-loader')
.tap(options => {
// 修改它的選項...
return options
})
}
}
```
## 4、編寫組件

統一暴露組件、指令、過濾器:
```
import Demo from "./components/demo"
import Transfer from "./components/transfer"
const components = [Demo, Transfer]; //組件
// const directives = [] // 指令
// const filters = [ ] //過濾器
//定義install方法,Vue作為參數
const install = Vue => {
console.log(Vue)
//判斷是否安裝,安裝過就不用繼續執行
if (install.installed) return;
install.installed = true;
//遍歷注冊所有組件
components.map(component \=> Vue.component(component.name, component));
//遍歷注冊所有指令
// directives.map(directives => Vue.use(directives));
//遍歷過濾器
// filters.map(filters => Vue.use(filters));
};
//檢測到Vue再執行
if (typeof window !== "undefined" && window.Vue) {
install(window.Vue);
}
export default {
install,
//所有組件,必須具有install方法才能使用Vue.use()
...components
};
```
## 5、庫模式打包
在package.json文件中的"scripts"字段里添加以下內容:
```
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lib": "vue-cli-service build --target lib --name llgtfoo-components-box -dest lib plugins/index.js",
"lint": "vue-cli-service lint"
},
```
## 6、.gitignore文件,
把包的一些測試文件過濾掉,最終打包只留下直接封裝的文件,即plugins中封裝的暴露組件
```
.DS_Store
node_modules
/dist
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
src/
plugins/
public/
vue.config.js
babel.config.js
*.map
*.html
```
## 7. 發布包
在終端執行,第一次發布:
```
npm login 登錄npm官網
npm run lib 打包
npm publish 發布
```
更新版本:
```
npm version patch 修改版本號version
npm publish 發布
```
```
patch:小變動,比如修復bug等,版本號變動 \*\*v1.0.0->v1.0.1\*\*
minor:增加新功能,不影響現有功能,版本號變動 \*\*v1.0.0->v1.1.0\*\*
major:破壞模塊對向后的兼容性,版本號變動 \*\*v1.0.0->v2.0.0\*\*
```
卸載包:
~~~bash
npm unpublish <package-name> -f
~~~
## 8、使用包
```
npm i xxxxxxxx
```

## 9、項目中實際使用
#### 9.1 安裝依賴
```
npm i npm-publish-test-jun123
```

#### 9.2 引入插件

#### 9.3 使用插件

#### 9.4 使用效果
