nuxt-community / router-module

Nuxt 2 module to use router.js instead of pages/ directory.
MIT License
401 stars 28 forks source link

Cannot extend routes from a module #121

Closed Angel21PC closed 2 years ago

Angel21PC commented 2 years ago

Hello friends, I have a problem with the routes in my Nuxt application, let me tell you. I am using the latest version of Nuxt (v2.15.8) and also the @nuxtjs/router (v1.7.0).

I'm trying to implement Domain-Driven Design in my application and I'm following this guide https://vueschool.io/articles/vuejs-tutorials/domain-driven-design-in-nuxt-apps/ , but I haven't got it working yet.

I am trying to implement it this way:

module/index.js

module.exports = function registerModule(moduleOptions) {
  this.extendRoutes((routes) => {
    routes.unshift({
      name: 'abc',
      path: '/abc',
      component: path.resolve(__dirname, 'pages/demoGuide.vue')
    })
  })
}

nuxt.config.js

  modules: [
    '~/modules/guides-module/index.js',
    ...
  buildModules: [
    [
      '@nuxtjs/router',
      {
        path: 'router',
        fileName: 'index.js',
        keepDefaultRouter: true
      }
    ]

router/index.js

/* eslint-disable no-console */
import Vue from 'vue'
import Router from 'vue-router'
import esRoutes from './routes-es'
import ptRoutes from './routes-pt'

Vue.use(Router)

export function createRouter(
  ssrContext,
  createDefaultRouter,
  routerOptions,
  config
) {
  const hostname = ssrContext ? ssrContext.req.headers.host : location.host
  const routes = getRoutes(hostname, config)

  return new Router({
    mode: 'history',
    routes,
    scrollBehavior(to, from, savedPosition) {
      const otherPageType = to.path !== from.path

      // Hay que tener en cuenta que con el paginado infinito se cambia la URL y puede afectar a esto
      if (
        !otherPageType &&
        (Object.keys(to.query).length !== 0 ||
          Object.keys(from.query).length !== 0)
      )
        return null

      // Default behavior
      return { x: 0, y: 0 }
    }
  })

  function getRoutes(hostname, config) {
    if (hostname === config.domainPt) return ptRoutes.concat(esRoutes)
    return esRoutes.concat(ptRoutes)
  }
}

When I try to access the route, I get a 404 as if it did not exist. Am I getting something wrong ? or is it not possible ? If anyone knows the solution, please let me know.

I have tried with a smaller project and got the same result. https://codesandbox.io/s/admiring-tree-v32b52?file=/nuxt.config.js:834-971

Thank you !