一、修改項目結構
-
當前結構
- 修改后結構
將原來的
src
目錄,修改成examples
新建packages
文件夾,用來存放后續的組件
二、修改配置
項目啟動默認入口是 src/main.js,第一步已將 src 文件名改成 examples 所以需要配置入口
- 已有
vue.config.js
文件
module.exports = {
pages: {
index: {
// 入口文件
entry: 'examples/main.js',
template: 'public/index.html',
filename: 'index.html'
}
}
}
- 沒有
vue.config.js
文件
在根目錄下新建此文件 配置pages
重新啟動項目 查看路徑是否正確并能正常啟動項目
三、開發組件
之前已經創建了一個
packages
目錄,用來存放組件
該目錄下存放每個組件單獨的開發目錄,和一個 index.js 整合所有組件,并對外導出
每個組件都應該歸類于單獨的目錄下,包含其組件源碼目錄 src,和 index.js 便于外部引用
以test
組件為例,完整的packages
如下
-
packages/test/src.main.vue
是組件的代碼 注意點: 一定要聲明name,name就是組件的標簽 -
packages/test/index.js
用于導出單個組件,如果要做按需引入,也需要在這里配置
// 導入組件,組件必須聲明 name
import Test from './src/main.vue'
// 為組件添加 install 方法,用于按需引入
Test.install = function (Vue) {
Vue.component(Test.name, Test)
}
// 默認導出組件
export default Test
-
packages/index.js
整合并導出組件,實現組件全局注冊
// 導入單個組件
import Test from './test/index.js'
// 以數組的結構保存組件,便于遍歷
const components = [
Test
]
// 定義 install 方法,接收 Vue 作為參數。如果使用 use 注冊插件,則所有的組件都將被注冊
const install = function (Vue) {
// 判斷是否安裝
if (install.installed) return
install.installed = true
// 遍歷并注冊全局組件
components.map(component => Vue.component(component.name, component))
}
// 判斷是否是直接引入文件
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue)
}
export default {
// 導出的對象必須具有 install,才能被 Vue.use() 方法安裝
install,
// 組件列表
...components
}
四、測試組件是否封裝成功
在examples/main.js中引入組件
// 這里的 TagTest 就是組件內定義的name
import TagTest from 'pack/index.js'
Vue.use(TagTest)
運行項目測試組件是否有bug
五、打包組件
在 package.json 里的 scripts 添加一個 lib 命令
"build:lib": "vue-cli-service build --target lib --name 生成的庫名 --dest lib packages/index.js"
運行 npm run build:lib
,編譯組件,成功后會在根目錄生成一個lib文件
六、發布
配置package.json
文件中發布到npm的字段
{
"name": "xxx", // 包名,該名字是唯一的。可在 npm 官網搜索名字,如果存在則需換個名字。
"version": "0.1.0", // 版本號,每次發布至 npm 需要修改版本號,不能和歷史版本號相同。
"description": "", // 描述
"main": "lib/xxx.umd.min.js", // 入口文件,該字段需指向我們最終編譯后的包文件。
"keyword": "", // 關鍵字,以空格分離希望用戶最終搜索的詞。
"private": false // 是否私有,需要修改為 false 才能發布到 npm
"author": "lh" // 作者
"license": "MIT" // 開源協議
在根目錄下新建.npmignore
文件,設置忽略發布文件
.DS_Store
node_modules/
examples/
packages/
public/
vue.config.js
babel.config.js
*.map
*.html
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw*
七、發布npm
- 切換鏡像
npm config set registry http://registry.npmjs.org
- 登陸npm
npm login
- 上傳發布
npm publish