# hb-third-lib

海豹常用第三方库，使用模块联邦实现

## 使用远程库

```javascript
yarn add hel-micro hb-third-lib
```

## 懒加载远程模块

```javascript
import helMicro from "hel-micro";

export async function bootstrap() {
  const lib = await helMicro.preFetchLib("hb-third-lib", {
    enableDiskCache: true,
    skip404Sniff: true,
    apiPrefix: "https://cdn.jsdelivr.net/npm",
    hook: {
      beforeAppendAssetNode(passCtx) {
        const { url, setAssetUrl } = passCtx;
        const jsdelivrUrl = url.replace(
          "https://unpkg.com",
          "https://cdn.jsdelivr.net/npm"
        );
        setAssetUrl(jsdelivrUrl);
      },
    },
  });
  return;
}
bootstrap().catch(() => false);
```

## 预加载远程模块

> src/loadApp.ts

```javascript
import { createApp } from "vue";
import App from "./App.vue";

const fn = async () => {
  const app = createApp(App);
  app.mount("#app");
};

fn().catch(() => false);
```

> src/main.ts

```javascript
import * as Vue from "vue";
import { bindVueRuntime, preFetchLib } from "hel-micro";
bindVueRuntime({ Vue });

async function bootstrap() {
  await preFetchLib("hb-third-lib", {
    skip404Sniff: true,
    // TODO: 可以替换cdn源
    skip404Sniff: true,
    apiPrefix: "https://cdn.jsdelivr.net/npm",
    hook: {
      beforeAppendAssetNode(passCtx) {
        const { url, setAssetUrl } = passCtx;
        const jsdelivrUrl = url.replace(
          "https://unpkg.com",
          "https://cdn.jsdelivr.net/npm"
        );
        setAssetUrl(jsdelivrUrl);
      },
    },
  }).catch(() => false);
  await import("./loadApp").catch(() => false);
}
void bootstrap().catch(() => false);
```

## 使用

```javascript
import { isArray } from "hb-third-lib";

function callRemoteMethod() {
  return isArray([]);
}
```

## 本地联调

进入 hb-third-lib 项目

```javascript
yarn start //启动项目
```

然后在宿主项目里

```javascript
async function bootstrap() {
  await preFetchLib("hb-third-lib", {
    custom: {
      host: "http://localhost:7001",
    },
    skip404Sniff: true,
    // apiPrefix: "https://cdn.jsdelivr.net/npm",
  }).catch(() => false);
  await import("./loadApp").catch(() => false);
}
void bootstrap().catch(() => false);
```

就可以愉快的本地联调啦

## 原理

你在宿主项目使用时，实践上只是使用了「hb-third-lib」导出的 lib 代理对象

```javascript
// proxy 代理对象
export const lib = exposeLib < LibProperties > LIB_NAME;

// 这里是我们为了方便使用而结构导出的
export const { hbUtils } = lib;

// 这里是我们为了方便使用而结构导出的
export const { isArray } = hbUtils;
```

而实际逻辑都是在客户端预加载的时候，才被加载进来，它们被存放在[hb-third-lib](https://unpkg.com/browse/hb-third-lib@0.0.12/)这个位置。

假设说，isArray 的逻辑有变，在「hb-third-lib」发布后，宿主项目不需要任何变动直接就能使用。

但如果 hbUtils 下新增了 isString 方法。

```javascript
// 这种使用方式，你就需要将「hb-third-lib」升级到最新版本
import { isArray, isString } from "hb-third-lib";

function callRemoteMethod() {
  return isArray([]) && isString("");
}
```

```javascript
// 这种使用方式，继续无视一切，直接使用就好了
import { hbUtils } from "hb-third-lib";

function callRemoteMethod() {
  return hbUtils.isArray([]) && hbUtils.isString("");
}
```
