Dynamic Routes

Universal Router Example

by Vladimir Kutepov

HTML

<script src="https://unpkg.com/[email protected]/universal-router.min.js"></script>

JavaScript

// https://github.com/kriasoft/universal-router
// import UniversalRouter from 'universal-router';

const routes = [
  {
    path: '/:module/:submodule',
    children: [], // match route path as `${path}*`
    action(context, params) {
      return _import(`./${params.module}/${params.submodule}/submoduleRoutes`)
        .then(routes => {
          context.route.children = routes.default;
          return context.next(); // go to children routes (render module or 404)
        })
        .catch(error => {
          if (error.message.startsWith('Cannot find module')) {
            return null; // module does not exists, so go to next route (or render 404)
          }
          throw error; // loading chunk failed (render error page)
        });
    },
  },
  {
    path: '*',
    action() {
      return 'Not Found';
    },
  },
];

const router = new UniversalRouter(routes);

router.resolve('/x/y/z')
  .then(result => {
    document.body.innerHTML = result;
  })
  .catch(error => {
    document.body.innerHTML = error.message;
  });

// use webpack import instead
function _import(path) {
  if (path !== './x/y/submoduleRoutes') {
    return Promise.reject(new Error(`Cannot find module '${path}.`));
  }
  return Promise.resolve({
    default: [ // export default moduleRoutes
	    { path: '/', action: () => 'Module Home Page' },
	    { path: '/z', action: () => 'Module Child Page' },
    ],
  });
}