提供静态资源服务的中间件(针对 publicDir 里面的文件)

    1. function servePublicMiddleware(dir: string): Connect.NextHandleFunction {
    2. // 通过 sirv 创建 public 的静态资源服务中间件
    3. const serve = sirv(dir, sirvOptions)
    4. return (req, res, next) => {
    5. // 如果是通过 import 获取资源,则直接跳过
    6. if (isImportRequest(req.url!)) {
    7. return next()
    8. }
    9. // 如果不是 import 则尝试在 publicDir 中获取静态资源,如果获取不到依旧会去下个中间件处理
    10. serve(req, res, next)
    11. }
    12. }
    13. // sirv 配置
    14. const sirvOptions: Options = {
    15. dev: true,
    16. etag: true,
    17. extensions: [],
    18. setHeaders(res, pathname) {
    19. // Matches js, jsx, ts, tsx.
    20. // The reason this is done, is that the .ts file extension is reserved
    21. // for the MIME type video/mp2t. In almost all cases, we can expect
    22. // these files to be TypeScript files, and for Vite to serve them with
    23. // this Content-Type.
    24. if (/\.[tj]sx?$/.test(pathname)) {
    25. res.setHeader('Content-Type', 'application/javascript')
    26. }
    27. }
    28. }
    29. // import 的请求蒲培
    30. const importQueryRE = /(\?|&)import(?:&|$)/
    31. isImportRequest = (url: string): boolean => importQueryRE.test(url)