midwayjs 组件静态资源映射默认页面问题

midwayjs 组件如果包含静态资源可以实现灵活的自服务开发,midwayjs 内部基于了koa-static-cache ,实际上是支持配置首页的

但是在测试的一些效果与实际的并不太符合,以下简单说明下原因

内部机制

alias 的处理,如下,可以看到如果有配置,实际会结合配置的alias 进一个filename的映射处理

 var filename = path.normalize(safeDecodeURIComponent(ctx.path))
    console.log('koa-static-cache request file:', filename);  
    // check alias
    console.log('koa-static-cache options.alias:', options.alias);
    if (options.alias && options.alias[filename]) filename = options.alias[filename];
    console.log('koa-static-cache mapped file:', filename);
    var file = files.get(filename)
    // try to load file
    if (!file) {
      if (!options.dynamic) return await next()
      if (path.basename(filename)[0] === '.') return await next()
      if (filename.charAt(0) === path.sep) filename = filename.slice(1)

具体就在alias 的映射上,并不是简单的机遇末尾规则的匹配,而且全部格式的匹配,所以如果组件包含了路径,那么alias 会需要路径的完整信息

参考配置

  • 不能生效的场景

与我们一般的理解不是一样的,/ 实际匹配的就是/ 并不包含/iot/ 部分

import {join} from 'path';

export  default {
  staticFile: {
    dirs: {
      default: {
        prefix: '/iot/',
        dir: join(__dirname, '../../iot'),
        alias: {
          '/': '/index.html'
        },
      },
    }
  }
}
  • 可以生效的处理

需要完整信息

import {join} from 'path';

export  default {
  staticFile: {
    dirs: {
      default: {
        prefix: '/iot/',
        dir: join(__dirname, '../../iot'),
        alias: {
          '/iot/': '/iot/index.html'
        },
      },
    }
  }
}

 

参考资料

https://midwayjs.org/docs/extensions/static_file

posted on 2025-11-23 08:00  荣锋亮  阅读(0)  评论(0)    收藏  举报

导航