基於Vue的組件化併發布到npm

在開始之前確保已經具備了Vue的開發環境。

創建項目

基於vue-cli腳手架創建項目。

 vue create le-baby

調整項目目錄結構

  1. 將src目錄改爲examples,用於組件的測試;

  2. 增加packages目錄,統一管理組件代碼文件。

  3. 項目結構如下:
    項目結構

修改打包配置

我們將src重命名爲examples,並添加packages目錄,用來存放我們的自定義組件。但是cli默認會啓動src下的服務,如果目錄名變了,我們需要手動修改配置。vue-cli中提供自定義打包配置項目的文件,如果沒有,我們只需要手動創建vue.config.js即可。具體修改如下:

module.exports = {
​    pages: {
​      index: {
​        entry: 'examples/main.js',
​        template: 'public/index.html',
​        filename: 'index.html'}},
​    // 擴展 webpack 配置,使 packages 加入編譯
​    chainWebpack: config => {
​      config.module
​        .rule('js')
​        .include
​          .add('/packages')
​          .end()
​        .use('babel')
​          .loader('babel-loader')}
}

編寫組件代碼

常規的vue組件封裝,此處就不給實例了。

編寫組件配置文件

假如我們編寫一個回到頂部的組件,配置如下:

//導入組件,確保from後路徑指向組件源碼文件
import LeBackToTop from './src/index'

// 爲組件提供 install 安裝方法,供按需引入
LeBackToTop.install = function (Vue) {
​    Vue.component(LeBackToTop.name, LeBackToTop)
}

// 導出組件
export default LeBackToTop

配置組件庫入口文件

在packages的入口文件index.js(如果沒有則自己創建)中導入組件並安裝導出

// 導入組件
import LeBackToTop from './back-to-top'
import LeStickyHeadList from './sticky-head-list'
import LeLogin from './login'
import LeCountDown from './count-down'

// 組件列表
const components = [
    LeBackToTop,
    LeStickyHeadList,
    LeLogin,
    LeCountDown
]

// 定義 install 方法,接收 Vue 作爲參數。如果使用 use 註冊插件,那麼所有的組件都會被註冊
const install = function (Vue) {
  // 判斷是否安裝
  if (install.installed) return
  // 遍歷註冊全局組件
  components.map(component => Vue.component(component.name, component))
}

// 判斷是否是直接引入文件
if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue)
}

export default {
  // 導出的對象必須具有 install,才能被 Vue.use() 方法安裝
  install,
  // 以下是具體的組件列表
  LeBackToTop,
  LeStickyHeadList,
  LeLogin,
  LeCountDown
}

組件測試

在example下進行組件測試。

  1. 導入組件庫
    main.js下導入組件庫。
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import LeBao from '../packages'

import App from './App.vue'

Vue.use(ElementUI)
Vue.use(LeBao)

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

tip:

 1. 必須引入Vue,即,`import Vue from 'vue'`
 2. 由於我的登錄組件中使用了element-ui,因此此處也引入了;
  1. 使用組件
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <!-- <le-login></le-login> -->
    <le-count-down ref="cCountDown" :show-day="true" :second="60" @timeup="timeupExe()"
      background-color="#f5f5f5" color="#FFA460" splitor-color="#ffa460"></le-count-down>
    <le-sticky-head-list :list-data='bisData'></le-sticky-head-list>
    <le-back-to-top ref="backToTop"></le-back-to-top>
  </div>
</template>

發佈插件庫

在驗證組件可用之後,我們要考慮如何發佈到npm上了,發佈前我們需要先對package.json、.npmignore和README.md進行修改。

配置package.json文件

package.json中主要配置了組件庫的基本信息和依賴情況。部分字段說明如下:

description:組件庫的描述文本
keywords:組件庫的關鍵詞
license:許可協議
repository:組件庫關聯的git倉庫地址
homepage:組件庫展示的首頁地址
main:組件庫的主入口地址(在使用組件時引入的地址)
private:聲明組件庫的私有性
scripts:可執行的腳本命令
author:作者
contributors:貢獻者

完整實例:

{
  "name": "le-bao",
  "description": "樂寶系列組件",
  "version": "0.0.9",
  "author": "Lele.Lee <[email protected]>",
  "license": "MIT",
  "private": false,
  "main": "lib/lebao.umd.min.js",
  "scripts": {
    "serve": "vue-cli-service serve --open",
    "build": "vue-cli-service build",
    //lib腳本說明:--target爲編譯文件輸出目錄;--name爲文件名前綴;--dest lib爲組件庫代碼入口文件;我們在命令行執行yarn lib命令,就會執行編譯腳本。
    "lib": "vue-cli-service build --target lib --name lebao --dest lib packages/index.js",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.19.2",
    "core-js": "^3.6.5",
    "element-ui": "^2.13.2",
    "node-sass": "^4.14.1",
    "sass-loader": "^8.0.2",
    "vue": "^2.6.11"
  },
  "bugs": {
    "url": "https://github.com/ysg-lijinwen/le-baby/issues",
    "email": "[email protected]"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/ysg-lijinwen/le-baby.git"
  },
  "contributors": [],
  "homepage": "https://github.com/ysg-lijinwen/le-baby.git",
  "keywords": [
    "component",
    "components",
    "樂寶組件",
    "優雅的按鈕",
    "vue",
    "vue-component",
    "Button",
    "design"
  ],
  "devDependencies": {
    "@vue/cli-plugin-babel": "^4.4.0",
    "@vue/cli-service": "^4.4.0",
    "vue-template-compiler": "^2.6.11"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}

關於README.md

用於插件發佈是,顯示插件信息、使用方法、相關命令等。REDAME.MD實例
5. 關於.npmignore文件
用於忽略不想發佈到npm的相關文件/文件夾資源。實例如下:

.DS_Store
node_modules/
dist/
node_modules/.bin/
build/
config/
static/
.babelrc
.editorconfig
.gitignore
.npmignore
.postcssrc.js
index.html
package-lock.json
npm-debug.log*
yarn-debug.log*
yarn-error.log*

#Editordirectoriesandfiles
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
#忽略目錄
examples/
packages/
public/
#忽略指定文件
vue.config.js
babel.config.js
*.map

發佈到npm服務

  1. 本地編譯組件
    發佈之前先在本地使用yarn lib進行編譯,確保能夠正常編譯組件到lib目錄下。
  2. 設置目標服務 npm config set registry https://registry.npmjs.org/
  3. 登錄npm login
  4. 發佈npm publish

可能的錯誤提示

E401錯誤

pm ERR! code E401
npm ERR! 401 Unauthorized - PUT http://registry.npmjs.org/le-plugin - You must be logged in to publish packages.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/lijinwen/.npm/_logs/2020-05-27T03_52_40_487Z-debug.log

這是未登錄的錯誤提示,重新執行登錄即可。登錄及登錄成功提示,如下:

lddeMacBook-Pro:le-plugin lijinwen$ npm login
Username: leelele
Password: 
Email: (this IS public) [email protected]
Logged in as leelele on http://registry.npmjs.org/.   //登錄成功提示

E402錯誤

402 Payment Required - PUT http://registry.npmjs.org/@le_bao%2fvui - You must sign up for private packages

這是因爲包名是“@xxx/xxxx”會被npm認爲要發佈私包,私包需要收費,需將發佈命令改成: npm publish --access public

E403錯誤

執行命令npm publish報錯:403 Forbidden - PUT https://registry.npmjs.org/kunmomotest2 - You cannot publish over the previously published versions: 0.0.1.

這是提示不能發佈以前發佈過的版本號,所以我們需要升版本號,修改package.json配置文件中的版本號(version),然後重新發布。

npm ERR! code E403
npm ERR! 403 403 Forbidden - PUT https://registry.npm.taobao.org/le-plugin - [no_perms] Private mode enable, only admin can publish this module
npm ERR! 403 In most cases, you or one of your dependencies are requesting
npm ERR! 403 a package version that is forbidden by your security policy.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/lijinwen/.npm/_logs/2020-05-27T03_50_52_679Z-debug.log

設置了淘寶鏡像導致的報錯,通過重新設置爲官方鏡像即可解決。設置命令npm config set registry http://registry.npmjs.org

E404錯誤

npm ERR! code E404
npm ERR! 404 Not Found - PUT http://registry.npmjs.org/@le_bao%2fvui - Scope not found
npm ERR! 404 
npm ERR! 404  '@le_bao/[email protected]' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404 
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/lijinwen/.npm/_logs/2020-05-27T08_40_37_702Z-debug.log

可能是npm版本有些低,使用npm install npm@latest -g更新npm就好了。

網絡問題引起的錯誤

可能的情況參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章