Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom Router #140

Closed
brillout opened this issue Aug 25, 2021 · 1 comment
Closed

Custom Router #140

brillout opened this issue Aug 25, 2021 · 1 comment
Labels
enhancement ✨ New feature or request

Comments

@brillout
Copy link
Member

brillout commented Aug 25, 2021

The new hook _onBeforeRoute() enables the integration of any router:

// _default.page.route.js

import { routeMatchesUrl } from 'some-router-library'

export { _onBeforeRoute }

function _onBeforeRoute(pageContext) {
  let match = null
  pageContext._pageRoutes.forEach(({pageId, pageRouteFile, filesystemRoute}) => {
    if( match ) {
      return
    }
    if (pageRouteFile) {
      const pageRoute = pageRouteFile.fileExports.default
      // Does `.page.route.js` export a Route String or Route Function?
      if (typeof pageRoute === 'string') {
        // We can use any logic we want, e.g. `some-router-library` could be Vue Router
        if (routeMatchesUrl(pageRoute, pageContext.url)) {
          match = pageId
          return
        }
      }
      if (typeof pageRoute === 'function') {
        // We can also handle Route Functions
        // ...
      }
    }
    // We can even implement something like Next.js' FileSystem parameterized routing `pages/product/[id].page`
    if (routeMatchesUrl(filesystemRoute, pageContext.url)) {
      match = pageId
      return
    }
    // Or simply non-parameterized FileSystem Routing:
    if (filesystemRoute === pageContext.url) {
      match = pageId
      return
    }
  })

  // Setting `pageContext._pageId` to `null` means 404.
  // Not setting or setting `pageContext._pageId` to `undefined` makes `vite-plugin-ssr` apply its usual
  // routing mechanism.
  return {
    pageContext: {
      _pageId: match
    }
  }
}

Users can "install plugins" simply by doing:

// _default.page.route.js

export * from '@vite-plugin-ssr/vue-router'

@gryphonmyers Is that enough for Vue Router? Am I missing something?

@brillout brillout added the enhancement ✨ New feature or request label Aug 25, 2021
@brillout
Copy link
Member Author

It's implementeed. You can see it in action at #136 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement ✨ New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant