海豹常用第三方库,使用模块联邦实现
yarn add hel-micro hb-third-lib
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
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
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);
import { isArray } from "hb-third-lib";
function callRemoteMethod() {
return isArray([]);
}
进入 hb-third-lib 项目
yarn start //启动项目
然后在宿主项目里
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 代理对象
// proxy 代理对象
export const lib = exposeLib < LibProperties > LIB_NAME;
// 这里是我们为了方便使用而结构导出的
export const { hbUtils } = lib;
// 这里是我们为了方便使用而结构导出的
export const { isArray } = hbUtils;
而实际逻辑都是在客户端预加载的时候,才被加载进来,它们被存放在hb-third-lib这个位置。
假设说,isArray 的逻辑有变,在「hb-third-lib」发布后,宿主项目不需要任何变动直接就能使用。
但如果 hbUtils 下新增了 isString 方法。
// 这种使用方式,你就需要将「hb-third-lib」升级到最新版本
import { isArray, isString } from "hb-third-lib";
function callRemoteMethod() {
return isArray([]) && isString("");
}
// 这种使用方式,继续无视一切,直接使用就好了
import { hbUtils } from "hb-third-lib";
function callRemoteMethod() {
return hbUtils.isArray([]) && hbUtils.isString("");
}