78 lines
2.1 KiB
TypeScript
78 lines
2.1 KiB
TypeScript
import { initialize, ITree } from "./initialize";
|
||
|
||
interface IMozzieOptions {
|
||
virtualModuleName?: string;
|
||
config?: any;
|
||
}
|
||
|
||
export interface IMeta {
|
||
name: string;
|
||
required: boolean;
|
||
type: string;
|
||
[key: string]: any;
|
||
}
|
||
|
||
export interface IRoute {
|
||
name: string;
|
||
path: string;
|
||
active: boolean;
|
||
}
|
||
|
||
export interface IConfigs {
|
||
config: {
|
||
title: string; // document title
|
||
subTitle: string; // 文档标题
|
||
};
|
||
}
|
||
|
||
export default function Bolt(options: IMozzieOptions) {
|
||
const { config = {} } = options;
|
||
const virtualModuleId = "virtual:@vite/plugin-bolt";
|
||
const resolvedVirtualModuleId = "\0" + virtualModuleId;
|
||
const TREE: ITree = {
|
||
compoTree: {},
|
||
fileTree: {},
|
||
routerList: [],
|
||
config: {},
|
||
};
|
||
return {
|
||
name: "@vite/plugin-bolt",
|
||
enforce: "pre",
|
||
resolveId(id: string) {
|
||
if (id === virtualModuleId) {
|
||
return resolvedVirtualModuleId;
|
||
}
|
||
},
|
||
load(id: string) {
|
||
if (id === resolvedVirtualModuleId) {
|
||
const { compoTree, fileTree, routerList } = initialize();
|
||
TREE.fileTree = fileTree;
|
||
TREE.compoTree = compoTree;
|
||
TREE.routerList = routerList;
|
||
TREE.config = config;
|
||
// build 后也存在 config
|
||
return `export const TREE = ${JSON.stringify(TREE)}`;
|
||
}
|
||
},
|
||
handleHotUpdate(ctx: any) {
|
||
const { file, server } = ctx;
|
||
//! 开发阶段:
|
||
//* 由于 上面load方法 只会触发一次,导致写到前端的 TREE 对象,无法更改
|
||
//* 当动态增减 components 组件,默认会先使用 TREE,然后触发 client:refresh 方法,获取到最新的 compoTree
|
||
//* 导致左侧菜单会变化,目前采用 loading 遮住这个跳变的过程
|
||
server.ws.send("server:fullUpdate", initialize());
|
||
|
||
//! return [] 会让 mdx-plugin 不更新
|
||
},
|
||
configureServer(server) {
|
||
server.ws.on("client:refresh", (data, client) => {
|
||
client.send("client:refresh:response", initialize());
|
||
});
|
||
},
|
||
transformIndexHtml(html) {
|
||
const { title } = config;
|
||
return html.replace(/<title>(.*?)<\/title>/, `<title>${title}</title>`);
|
||
},
|
||
};
|
||
}
|