type SetupMiddlewaresServer = {
sockWrite: (
type: string,
data?: string | boolean | Record<string, any>,
) => void;
environments: {
[name: string]: {
/**
* 获取当前环境的构建信息
*/
getStats: () => Promise<Stats>;
/**
* 在服务端加载并执行构建产物
*
* @param entryName - 入口名称,和 Rsbuild source.entry 的某一个 key 值对应
* @returns 入口模块的返回值
*/
loadBundle: <T = unknown>(entryName: string) => Promise<T>;
/**
* 获取编译后的 HTML 模版内容
*/
getTransformedHtml: (entryName: string) => Promise<string>;
};
};
};
type SetupMiddlewares = Array<
(
middlewares: {
unshift: (...handlers: RequestHandler[]) => void;
push: (...handlers: RequestHandler[]) => void;
},
server: SetupMiddlewaresServer,
) => void
>;
undefined
提供执行自定义函数和应用自定义中间件的能力。
中间件的执行顺序是: unshift
=> 内置中间件 => push
。
export default {
dev: {
setupMiddlewares: [
(middlewares, server) => {
middlewares.unshift((req, res, next) => {
next();
});
middlewares.push((req, res, next) => {
next();
});
},
],
},
};
一些特殊场景需求可能需要使用服务器 API:
export default {
dev: {
setupMiddlewares: [
(middlewares, server) => {
// 添加自定义 watcher 并在文件更新时触发页面刷新
watcher.on('change', (changed) => {
server.sockWrite('content-changed');
});
},
],
},
};
export default {
dev: {
setupMiddlewares: [
(middlewares, server) => {
middlewares.unshift(async (req, _res, next) => {
const webStats = await server.environments.web.getStats();
console.log(webStats.toJson({ all: false }));
next();
});
},
],
},
};