2023-10-30 21:30:29 +08:00
|
|
|
import type { Plugin } from "vite";
|
2023-10-13 17:24:28 +08:00
|
|
|
import { createEps } from "./eps";
|
|
|
|
import { createModule } from "./module";
|
|
|
|
|
|
|
|
export function virtual(): Plugin {
|
|
|
|
const virtualModuleIds = ["virtual:eps", "virtual:module"];
|
|
|
|
|
2023-11-24 15:08:24 +08:00
|
|
|
// 首次启动加载 Eps
|
|
|
|
createEps();
|
|
|
|
|
2023-10-13 17:24:28 +08:00
|
|
|
return {
|
|
|
|
name: "vite-cool-virtual",
|
|
|
|
enforce: "pre",
|
|
|
|
configureServer(server) {
|
|
|
|
server.middlewares.use(async (req, res, next) => {
|
2023-10-30 21:30:29 +08:00
|
|
|
// 页面刷新时触发
|
2023-10-13 17:24:28 +08:00
|
|
|
if (req.url == "/@vite/client") {
|
2023-10-30 21:30:29 +08:00
|
|
|
// 重新加载虚拟模块
|
|
|
|
virtualModuleIds.forEach((vm) => {
|
|
|
|
const mod = server.moduleGraph.getModuleById(`\0${vm}`);
|
|
|
|
|
|
|
|
if (mod) {
|
|
|
|
server.moduleGraph.invalidateModule(mod);
|
|
|
|
}
|
|
|
|
});
|
2023-10-13 17:24:28 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
},
|
2023-10-30 21:30:29 +08:00
|
|
|
async handleHotUpdate({ file, server }) {
|
|
|
|
// 代码保存时触发
|
2024-04-21 11:29:45 +08:00
|
|
|
if (!["dist"].some((e) => file.includes(e))) {
|
|
|
|
createEps().then((data) => {
|
|
|
|
// 通知客户端刷新
|
|
|
|
server.ws.send({
|
|
|
|
type: "custom",
|
|
|
|
event: "eps-update",
|
|
|
|
data
|
|
|
|
});
|
2023-10-26 17:15:08 +08:00
|
|
|
});
|
2023-10-13 17:24:28 +08:00
|
|
|
}
|
|
|
|
},
|
|
|
|
resolveId(id) {
|
|
|
|
if (virtualModuleIds.includes(id)) {
|
|
|
|
return "\0" + id;
|
|
|
|
}
|
|
|
|
},
|
|
|
|
async load(id) {
|
|
|
|
if (id === "\0virtual:eps") {
|
2023-10-30 21:30:29 +08:00
|
|
|
const { service } = await createEps();
|
2023-10-13 17:24:28 +08:00
|
|
|
|
|
|
|
return `
|
2023-10-30 21:30:29 +08:00
|
|
|
export const eps = ${JSON.stringify({ service })}
|
2023-10-13 17:24:28 +08:00
|
|
|
`;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (id === "\0virtual:module") {
|
|
|
|
const { dirs } = createModule();
|
|
|
|
|
|
|
|
return `
|
|
|
|
export const dirs = ${JSON.stringify(dirs)}
|
|
|
|
`;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|