提供静态资源服务的中间件(针对 publicDir 里面的文件)
function servePublicMiddleware(dir: string): Connect.NextHandleFunction {
// 通过 sirv 创建 public 的静态资源服务中间件
const serve = sirv(dir, sirvOptions)
return (req, res, next) => {
// 如果是通过 import 获取资源,则直接跳过
if (isImportRequest(req.url!)) {
return next()
}
// 如果不是 import 则尝试在 publicDir 中获取静态资源,如果获取不到依旧会去下个中间件处理
serve(req, res, next)
}
}
// sirv 配置
const sirvOptions: Options = {
dev: true,
etag: true,
extensions: [],
setHeaders(res, pathname) {
// Matches js, jsx, ts, tsx.
// The reason this is done, is that the .ts file extension is reserved
// for the MIME type video/mp2t. In almost all cases, we can expect
// these files to be TypeScript files, and for Vite to serve them with
// this Content-Type.
if (/\.[tj]sx?$/.test(pathname)) {
res.setHeader('Content-Type', 'application/javascript')
}
}
}
// import 的请求蒲培
const importQueryRE = /(\?|&)import(?:&|$)/
isImportRequest = (url: string): boolean => importQueryRE.test(url)