手把手教你寫一個 Vue 組件發佈到 npm 且可外鏈引入使用

前言

我們爲什麼要寫個組件上傳到npm鏡像上呢,我們肯定遇到過這樣一個場景,項目中有很多地方與某個功能相似,你想到的肯定是把該功能封裝成Component組件,後續方便我們調用。但是過了一段時間,你的Leader讓你去開發另一個項目,結果你在哪個項目中又看見了類似的功能,你這時會怎麼做?   你也可以使用Ctrl + c + v大法,拿過來上一個項目封裝好的代碼,但是如果需求有些變動,你得維護兩套項目的代碼,甚至以後更多的項目....,這時你就可以封裝一個功能上傳到你們公司內網的npm上 (或者自己的賬號上),這樣每次遇到類似的功能直接npm install 安裝import導入進來使用就可以,需求有變動時完全可以改動一處代碼。

配置環境

筆者這裏使用的是Webpack配置 (有點菜,不要介意),也可以安裝一個Vue-cli簡單版的,它那裏面有暴露Webpack的配置 (也得修改自行配置),我們來配置一下打包組件環境,一般開發組件庫都是使用的umd格式,這種格式支持Es ModuleCommonJsAMD三種引入方式使用,主要就是Webpack裏的librarylibraryTarget,如果不明白的看這裏詳解 webpack 的 out.libraryTarget 屬性

我這裏的 Webpack 版本爲 4,  最好跟着本章裏的插件版本號進行安裝,避免出現版本兼容問題

項目結構

|- /node_modules
|- /src
   |- Tag.vue
   |- main.js
|- index.html
|- webpack.config.js
|- package.json

初始化 Package.json

npm init -y

安裝 Webpack && Loader && Plugin

cnpm i webpack webpack-cli -D
cnpm i css-loader style-loader -D
cnpm i file-loader -D
cnpm i vue-loader@15.7.0 vue vue-template-compiler -D
cnpm i html-webpack-plugin@3.2.0 -D

webpack.config.js

const VueLoaderPlugin = require('vue-loader/lib/plugin')
const HtmlWebpackPlugin = require("html-webpack-plugin")
module.exports = {
    mode: "development",
    entry: "./src/main.js",
    output: {
        filename: "index.js"
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ["style-loader""css-loader"]  
            },
            {
                test: /\.(ttf|eot|woff|svg|woff2)/,
                use: "file-loader"
            },
            {
                test: /\.vue$/,
                use: "vue-loader"
            }
        ]
    },
    plugins: [
        new VueLoaderPlugin(),
        new HtmlWebpackPlugin({
            template: "./index.html"
        })
    ]
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta >
    <title>Document</title>
</head>
<body>
    <div id="app"></div>
</html>

以上我們基本環境就搭建完啦,可以在終端使用npx webpack運行看看哦。

封裝組件

我這裏只做一個示例哈,代碼就不寫那麼複雜,大家知道怎麼打包使用就行,具體封裝成啥樣看你們公司需求啦~。筆者這裏使用Element Ui組件來做一個示例,相信大部分小夥伴公司也在使用Element Ui。假如我們項目中有以下類似的功能就可以單獨封裝起來。

示例

main.js

import Vue from 'vue'
import { Tag } from 'element-ui';
import 'element-ui/lib/theme-chalk/tag.css';
import Tag from './Modal.vue'
Vue.component(Tag.name, Tag)
export default Tag

Tag.vue

<template>
  <div class="Tag">
    {{ msg }}
    <el-tag type="success">標籤二</el-tag>
  </div>
</template>

<script>
export default {
 name: 'Tag',
  data() {
    return {
        msg: "hello 蛙人",
    }
  },
  created() {
  },
  components: {},
  watch: {},
  methods: {
  }
}
</script>
<style scoped>

</style>

Webpack.config.js

webpack.config.js裏的output修改爲如下

output: {
    filename: "index.js",
    library: "Modal",
    libraryTarget: "umd"
}

配置完之後就可以使用npx webpack打包,可以看到有一個dist目錄,該目錄下存在一個index.js,  這個文件就是我們封裝的Tag.vue文件, 你可以將它引入到你的項目中,進行調用,該文件支持Es ModuleCommonJsAMD三種方式引入。

import Vue from 'vue'
import { Tag } from 'element-ui';
import 'element-ui/lib/theme-chalk/tag.css';
Vue.component(Tag.name, Tag)
import CustomTag from "./index" // 打包完的,直接引入進來
new Vue({
    el: "#app",
    render: h => h(CustomTag)
})

Npm 發佈

如果沒有npm賬號呢,先去官網註冊一個npm賬號這裏

新建一個發佈包項目文件夾

在終端執行npm init -y ,進行初始package.json文件,主要信息就是 name 和 main 字段,前者是這個包的名稱 (也就是 npm instal xxx),後者則是我們打包好的文件Tag文件,默認main就去找這個入口文件。

注意:包名稱不能包含大寫,包名稱不能包含大寫,包名稱不能包含大寫,重要的事情說三遍

{
  "name""custom-tag-waren",
  "version""1.0.0",
  "description""這是xxxx",
  "main""index.js",
  "scripts"{
    "test""echo \"Error: no test specified\" && exit 1"
  },
  "keywords"[],
  "author""WaRen",
  "license""ISC"
}

如果淘寶鏡像之前被更改,先改回來執行以下命令

npm config set registry http://registry.npmjs.org

註冊完之後,執行npm login, 依次填寫你的用戶名密碼郵箱

執行npm publish發佈,然後等待進度條完成即可。

整理一些常見的發佈錯誤

這是因爲鏡像設置成淘寶鏡像了,設置回來即可

no_perms Private mode enable, only admin can publish this module

一般是沒有登錄,重新登錄一下 npm login 即可

npm publish failed put 500 unexpected status code 401

包名被佔用,改個包名即可,最好在官網查一下是否有包名被佔用,之後再重命名

npm ERR! you do not have permission to publish “your module name”. Are you logged in as the correct user?

郵箱未驗證,去官網驗證一下郵箱

you must verify your email before publishing a new package

npm 安裝使用

cnpm i custom-tag-waren -D

main.js

import Vue from 'vue'
import { Tag } from 'element-ui';
import 'element-ui/lib/theme-chalk/tag.css';
import customTagWaren from "custom-tag-waren"  // 下載完引入進來
Vue.component(Tag.name, Tag)
new Vue({
    el: "#app",
    render: h => h(customTagWaren)
})

到此爲止就完成了一個組件的打包上傳下載,這樣我們在每個項目需要的時候直接npm install安裝就行,當需求改動的時候只改一個文件然後再次發佈就行。是不是很方便啦。

外鏈引入

我們也不上傳npm上,直接使用外鏈的形式使用,下面我們來看看

import 引入

<template>
  <div class="Tag">
    <TagEl/>
  </div>
</template>

<script>
import TagEl from "./index"
export default {
 name: 'Tag',
  data() {
    return {
       
    }
  },
  components: {
      TagEl
  },
}
</script>
<style scoped>

</style>

上面example中,我們看到直接引入了index.js文件並進行註冊組件,直接就可以使用啦。

script 引入

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta >
    <title>Document</title>
</head>
<body>
    <div id="app">
        <Tag/>
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
    <script type="text/javascript" src="./dist/index.js"></script>
</body>
<script>
    new Vue({
        el: "#app",
        components: {
            Tag: Tag.default
        }
    })
</script>
</html>

上面example中,直接使用script標籤引入進來,也是註冊完使用就可以。那麼我們怎麼知道他名字是 Tag,這個你在封裝組件的使用,必須指定 Name 名稱。

export default {
 name: "Tag"
}

參考資料

https://blog.csdn.net/weixin_43606158/article/details/1068086
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/vfOmxqSRSbZQbDt9yGUrUA