1
votes

I have a file exporting my VueRouter instance:

// src/js/router.js

import VueRouter from "vue-router";

export default new VueRouter({
  mode: "history",
  routes: [
    {
      name: "home",
      path: "/",
      component: "./component/Home.vue"
    },
    {
      name: "contact-us",
      path: "/contact-us",
      component: "./component/ContactUs.vue"
    }
  ]
});

ATTEMPT

I tried to execute this file:

// test.js

import router from "./src/js/router.js";

Using node:

node --experimental-modules test.js

But I ran into this error:

$ node --experimental-modules test.js (node:13688) ExperimentalWarning: The ESM module loader is experimental. C:\xampp\htdocs\extract-routes-from-vue-router\test.js:1 (function (exports, require, module, __filename, __dirname) { import router from > "./src/js/router.js"; ^^^^^^

SyntaxError: Unexpected identifier at new Script (vm.js:80:7) at createScript (vm.js:274:10) at Proxy.runInThisContext (vm.js:326:10) at Module._compile (internal/modules/cjs/loader.js:664:28) at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10) at Module.load (internal/modules/cjs/loader.js:600:32) at tryModuleLoad (internal/modules/cjs/loader.js:539:12) at Function.Module._load (internal/modules/cjs/loader.js:531:3) at createDynamicModule (internal/modules/esm/translators.js:73:15) at Object.meta.done (internal/modules/esm/create_dynamic_module.js:42:9)

QUESTION

How can I extract only the path keys from the router? I would like to generate a sitemap based on my router routes.

1

1 Answers

0
votes

There is an example on this site to get all routes as an array of links:

const router = new Router({ /* Your Router config go here */ });

function getRoutesList(routes, pre) {
  return routes.reduce((array, route) => {
    const path = `${pre}${route.path}`;

    if (route.path !== '*') {
      array.push(path);
    }

    if (route.children) {
      array.push(...getRoutesList(route.children, `${path}/`));
    }

    return array;
  }, []);
}

getRoutesList(router.options.routes, 'https://zigamiklic.com');

Example output:

[
   'https://zigamiklic.com/home',
   'https://zigamiklic.com/settings/',
   'https://zigamiklic.com/settings/general',
   'https://zigamiklic.com/settings/profile',
   'https://zigamiklic.com/contact',
]

If you don't need the prefix, you could use it like this:

getRoutesList(router.options.routes, '');