一: 如何快速搭建一個組件庫
首先,我們介紹一個快速包裝組件庫的工具:https://github.com/yanhaijing/jslib-base

按照文檔來,就簡單幾步:
npx @js-lib/cli mylib
jslib new mylib
然后我們src 目錄添加我們自己的文件庫,然后以 index.js 導(dǎo)出文件。
例如:

index.js 是對外提供了函數(shù)或者變量接口
// import 'babel-polyfill';
import jsBridge from './utils/js-bridge';
import * as htmlUtils from './utils/html-utils';
import DOMAIN from './utils/DOMAIN';
import LS from './utils/local-storage';
import { uSmartInit } from './utils/init';
import setTitleBar from './utils/set-title-bar';
import toRsa from './utils/rsa'
import i18n from './utils/plugins/yx-i18n/index'
export {
jsBridge,
htmlUtils,
DOMAIN,
LS,
uSmartInit,
setTitleBar,
toRsa,
i18n
};
我們執(zhí)行npm run build ,進行打包
npm run build
# 發(fā)布到遠程
git push
然后打 tag之后,生成對外下載的鏈接,我們以 gitlab 為例

二:使用組件庫
本地項目按照組件庫,使用以下方式,獲取最新修改的庫
// 添加
// yarn add git+<倉庫地址>#<tag版本號>,例如
yarn add git+ssh://git@szgitlab.name.com:222567575/web/base-h5.git#v1.0.1
// 更新的時候,可以先刪除 老包,然后安裝新包,主要是 tag 的改動,例如
yarn remove git+ssh://git@szgitlab.name.com:222567575/web/base-h5.git#v1.0.1
yarn add git+ssh://git@szgitlab.name.com:222567575/web/base-h5.git#v1.0.2
以上是生成一個 npm 包的流程。
知識附錄:
1: npm package git URL formants
npm package git URL formants 可以參考 npm 文檔

由于npm有緩存機制,所以,當(dāng)你更新完庫的代碼的時候,執(zhí)行 npm install 并不會拉取最新的代碼,所以我們可以打 tag 的形式實現(xiàn)更新。
2: 關(guān)于模塊npm 官方給出了明確的定義
A module is any file or directory in the node_modules directory that can be loaded by the Node.js require() function.
To be loaded by the Node.js require() function, a module must be one of the following:
- A folder with a package.json file containing a "main" field.
- A JavaScript file.
注意: 不是所有的模塊都要求包含一個package.json文件,因為不是所有的模塊都是 npm包,但是 npm 包一定是包含package.json的模塊。
在 node 程序的上下文中,模塊也可以是從一個文件加載而來的。例如
var req = require('request')
我們可以說“變量req指向請求模塊”