Nuxt.js: Unable to automatically generate routing configuration
P粉404539732
2023-08-25 13:31:01
<p>I want to generate static routes (<code>/contact</code>, <code>/about</code>,...) and dynamic routes (<code>/project /1</code>, <code>/project/2</code>, ...) so that when the user refreshes the page while accessing one of these routes, the page still works correctly. </p>
<p>But when executing <code>npm run generate</code>, I only get the <code>generated route "/"</code>, in <code>/dist</code> The generated routes are not visible in the folder. </p>
<p>Nuxt.js version used: <code>2.14.7</code></p>
<p>I tried both modes, <code>universal</code> and <code>spa</code>, neither worked. </p>
<p>In the nuxt.config.js file, I added the following code at the top: </p>
<pre class="brush:js;toolbar:false;">const axios = require('axios')
const dynamicRoutes = async () => {
const routes = await axios.get('http://my-project.com/wp/wp-json/projects/v1/posts')
.then(res => res.data.map((project) => `/project/${project.ID}/${project.post_name}`))
.then(res => res.concat(
[
'/about',
'/contact',
'/portfolio'
]
))
return routes
}
</pre>
<p>Then in <code>export default {}</code>: </p>
<pre class="brush:js;toolbar:false;">generate: {
routes: dynamicRoutes
},
</pre>
<p><br /></p>
First of all, you don't need to add
mode: 'universal'
to the configuration, just addtarget: 'static'
to simplify the configuration. Learn more - https://nuxtjs.org/docs/2.x/features/deployment-targets/. Withssr: true
you will get a fully static mode website with relevant hooks as described in https://stackoverflow.com/a/65208463/8153537.Next, you can remove the @nuxt/router module. Check out my gist - https://gist.github.com/MexsonFernandes/d04495c86b115bbe29f26b36b0b35d2d. Nuxt generates all required routes based on the folder structure, so no additional configuration is required.
Check out this gist for project page routing - https://gist.github.com/MexsonFernandes/d04495c86b115bbe29f26b36b0b35d2d#gistcomment-3555332.
router.mode='hash'
appears to be incompatible with thegenerate.routes
configuration. Whenrouter.mode
is set tohash
, the Nuxt generator ignores generate.routes and only creates a route for/
, this is probably because the homepage is only expected to exist inhash
mode (i.e.index.html
has a route set up that handles all routes for the application).This hash mode also conflicts with the mode set in router.js, but if you really need hash routing, you should choose only in
router.js
Set this in # to allow processing ofgenerate.routes
.Also note that
mode='universal'
is equivalent tossr=true
, so the configuration ssr=false is not available in this mode significance. If generating a static site, you needssr=true
so that anyasyncData()
andfetch()
hooks can be called to populate the static page data. This setup also eliminates the need to add /about,
/contactand
/portfolioin
dynamicRoutes()
# because they are already included in the generated route.GitHub PR