【问题标题】:NuxtJS Static generated HTML page does not load Javascript when calling /index.htmlNuxtJS 静态生成的 HTML 页面在调用 /index.html 时不加载 Javascript
【发布时间】:2020-09-03 08:27:45
【问题描述】:

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

当我将页面与 npm run dev 一起使用时,一切正常。

使用 npm run build && npm run generate 导出后,我将生成的内容从 /dist 部署到我的服务器(用户请求的 CDN,在这种情况下是 Google Cloud Storage)我可以使用该页面而无需如果我不添加 index.html 后缀会出现任何问题。

例子:

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

但是

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

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

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

有什么想法吗?

【问题讨论】:

    标签: javascript vue.js nuxt.js server-side-rendering


    【解决方案1】:

    更新

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

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

    通过在nuxt-config中扩展router,理论上可以根据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 帖子中截取了这个,它在生产和测试中完美运行。

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 2020-11-30
      • 1970-01-01
      • 2021-07-11
      • 2017-01-12
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      相关资源
      最近更新 更多