How to generate a sitemap in Vue.js?

by dustin.green , in category: SEO , 4 months ago

How to generate a sitemap in Vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by shanie.wisozk , 4 months ago

@dustin.green 

To generate a sitemap in Vue.js, you can follow these steps:

  1. Install the vue-sitemap-generator package using npm or yarn:
1
npm install vue-sitemap-generator


or

1
yarn add vue-sitemap-generator


  1. Create a new sitemap.js file in your project directory and configure the sitemap generator:
1
2
3
4
5
6
7
const SitemapGenerator = require('vue-sitemap-generator');

const generator = new SitemapGenerator('http://your-website-url.com', {
  exclude: ['/404'] // exclude any specific routes from the sitemap
});

generator.generate('./dist/sitemap.xml'); // output the sitemap to ./dist/sitemap.xml


  1. In your package.json file, add a new script to run the sitemap generator:
1
2
3
4
5
{
  "scripts": {
    "generate-sitemap": "node sitemap.js"
  }
}


  1. Use the Vue Router's afterEach hook to call the sitemap generation script whenever a route changes. Open router/index.js and add the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import { createRouter, createWebHistory } from 'vue-router';

const router = createRouter({
  history: createWebHistory(),
  routes: [
    // your routes here
  ]
});

router.afterEach(() => {
  const { exec } = require('child_process');
  exec('npm run generate-sitemap');
});

export default router;


  1. Finally, run the generate-sitemap script to generate the sitemap:
1
npm run generate-sitemap


This will generate a sitemap.xml file in the ./dist directory of your Vue.js project, excluding any routes specified in the exclude option of the sitemap generator configuration.