Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm working on a nuxtjs project which will be generated for static usage. Of course it uses Javascript for e.g. the Navigation, some forms and more.

When I am using the page with npm run dev everything works fine.

After exporting with npm run build && npm run generate I deploy the generated content from /dist to my server (cdn requested by user, in that case Google Cloud Storage) I can use the page without any problems if I dont add the index.html suffix.

Example:

Visiting https://page.com/subpage/ works fine

but

Visiting https://page.com/subpage/index.html not really.

Yes it renders the content with CSS and DOM, but Javascript is not working at all. In the Dev-Tools of Google Chrome I can see that in both cases the javascript seems to be loaded, but not called in the second scenario. See attached Screenshots. Both were similar.

Dev-Tools

My nuxt-Config is almost empty regarding render, build-configurations. I just disabled ressourceHints and that's all. I'm not sure if this is an issue with the router only accepting the folder itself containing the index.html.. The router paths are generated dynamically by nuxtLinks.

Any ideas?

like image 858
l9cgv Avatar asked Sep 03 '20 08:09

l9cgv


1 Answers

Update

After searching for answers for about another 1-2 hours, I finally found a solution.

There is a way to add the index.html suffix to the router as an alias for each paths.

By extending the router in the nuxt-config, you can theoretically add an alias based on the router-path. It is not always the best way, but it works quite well in that situation.

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
    })
  }
}

I got this snipped from the reddit post by animagnam (https://www.reddit.com/r/Nuxt/comments/gzwrqu/visiting_generated_site_routes_with_trailing/ftnylrt?utm_source=share&utm_medium=web2x&context=3) and it works perfectly in production and tests.

like image 154
l9cgv Avatar answered Sep 27 '22 17:09

l9cgv