调用 /index.html 时,NuxtJS 静态生成 HTML 页面未加载 Javascript

NuxtJS Static generated HTML page does not load Javascript when calling /index.html

我正在开发一个 nuxtjs 项目,该项目将为静态使用而生成。当然它使用 Javascript 例如导航、一些表单等等。

当我使用带有 npm 运行 dev 的页面时,一切正常。

使用 npm 运行 build && npm 运行 generate 导出后,我将生成的内容从 /dist 部署到我的服务器(用户请求的 cdn,在那种情况下 Google 云存储)如果我不添加 index.html 后缀,我可以毫无问题地使用该页面。

示例:

访问 https://page.com/subpage/ 正常

但是

来访 https://page.com/subpage/index.html 不是真的。

是的,它使用 CSS 和 DOM 呈现内容,但 Javascript 根本不起作用。在 Google Chrome 的开发工具中,我可以看到在这两种情况下 javascript 似乎已加载,但在第二种情况下未被调用。请参阅随附的屏幕截图。两者很相似。

关于渲染、构建配置,我的 nuxt-Config 几乎是空的。我只是禁用了 ressourceHints,仅此而已。我不确定这是否是路由器仅接受包含 index.html 的文件夹本身的问题。路由器路径由 nuxtLinks 动态生成。

有什么想法吗?

更新

又找了大概1-2个小时的答案,终于找到了解决办法。

有一种方法可以将 index.html 后缀添加到路由器作为每个路径的别名。

通过扩展nuxt-config中的路由器,理论上可以在router-path的基础上添加别名。它并不总是最好的方法,但在那种情况下效果很好。

router: {
  extendRoutes(routes) {
    routes.forEach((route) => {
      // When options.generate.subFolders is true (default)
      const alias =
        route.path.length > 1 ? `${route.path}/index.html` : '/index.html'
      // When options.generate.subFolders is false
      // const normalizedRoute = route.path.replace(/\/$/, '') // Remove trailing slashes if they exist
      // const alias =
      //   route.path.length > 1 ? `${normalizedRoute}.html` : '/index.html'
      route.alias = alias
    })
  }
}

我从 animagnam (https://www.reddit.com/r/Nuxt/comments/gzwrqu/visiting_generated_site_routes_with_trailing/ftnylrt?utm_source=share&utm_medium=web2x&context=3) 的 reddit post 中截取了这个片段,它在生产和测试中完美运行。