¿Cómo genera nuxt un mapa del sitio estático y dinámico sitemap.xml?

prefacio

La función de sitemap.xml es incluir todas las páginas de nuestro sitio web mediante SEO (motor de búsqueda del navegador), el contenido de nuestro sitio web es más fácil de buscar por los usuarios y, al mismo tiempo, aumenta la popularidad de nuestro sitio web y ocupa un lugar más alto. En resumen, se trata de utilizar tecnología para promocionar el sitio web, por lo que la tecnología del mapa del sitio de promoción del sitio web sigue siendo muy importante. El proceso de implementación es un poco engorroso, pero no es difícil. Comencemos el tutorial de hoy.

Procedimientos de operación

1. Dependencias de instalación

npm install @nuxtjs/sitemap

Este enlace es la documentación oficial del mapa del sitio en npm

2. Abra nuxt.config.js y agregue sus dependencias para representar todo nuestro proyecto usando esta dependencia.

注意:之前引入的依赖不用删,只需要将sitemap加在后面

{
    
    
  modules: [
    '@nuxtjs/sitemap'
  ],
}

3. Ingrese a la carpeta estática, cree sitemap.js, el contenido es el siguiente

1. Explicación de cada elemento de configuración
import axios from "axios";  // 引入axios,动态生成站点地图需要用到
const sitemap = {
    
    
  path: "/sitemap.xml", //生成的文件路径
  hostname: "http://www.baidu.com/", // 你的网站地址
  cacheTime: 1000 * 60 * 60 * 24, //一天的更新频率,只在generate:false有用
  gzip: true, //用gzip压缩优化生成的 sitemap.xml  文件 
  generate: false, 
  exclude: [], //排除不需要收录的页面,这里的路径是相对于hostname, 例如: exclude: ['/404',...]
  // 每个对象代表一个页面,这是默认的
  defaults: {
    
    
    changefred: "always", // 收录变化的时间,always 一直,daily 每天
    lastmod: new Date(), // 生成该页面站点地图时的时间
    priority: 1, // 网页的权重  1是100%最高,一般给最重要的页面,不重要的页面0.7-0.9之间
  },
  routes: async () => {
    
    
    return routes
  },
};
export default sitemap;
2. Generar código estático

这里主要放那种不需要携带的页面,示例: http://www.baidu.com/pressCenter,每个对象的url的前缀是自动相对上面hostname网站地址的,所以只需要写你的路由就行。

 routes: async () => {
    
    
    // 静态路由
    let routes = [
      {
    
    
        url: `/`,
        changefred: "daily",
        lastmod: new Date(),
        priority: 1,
      },
      {
    
    
        url: `/pressCenter`,
        changefred: "daily",
        lastmod: new Date(),
        priority: 0.9,
      },
    ];
    return routes
   }
3. Generar código dinámico

动态指的是类似详情页这种 http://www.baidu.com/detail?id=1 ,这种是根据后端数据自动生成的,不可能手动一个一个去加,那样就太机械了,不符合我们写程序的风格,所以这一小节就是讲如何生成动态站点地图。

    let axiosUrl = "你的接口请求前缀";  // 示例 "http://www.baidu.cn/api/"
    let prodRoutes = [];
    let newsRoutes = [];

    // Promist.all并发调接口  所有异步接口同时调用,缩短生成站点地图的时间,通过解构取出接口返回的数据
    let [productList, newsList] = await Promise.all([
      axios.get(axiosUrl + "product/list"),
      axios.get(axiosUrl + "news/list"),
    ]);
   
    // 商品详情   
    /* 200状态码判断这块属于代码优化  成功才进来,否则之间打印错误信息,由于nuxt有时出问题能提供给我们的信息非常匮乏,
    	假设某天接口出问题,到时很难定位问题,所以加这个主要是方便我们后期的维护。  */
    if (productList.data.code == 200) {
    
    
      let proList = productList.data.rows; // 这个对应接口返回的列表
      // 用map将列表里的每个对象的id组装同时生成新的对象,每个对象生成后的样子,见下面标注1
      prodRoutes = proList.map((item) => {
    
    
        return {
    
    
          url: `/product/twoPage/threePage?id=${
      
      item.id}`,
          changefred: "daily",
          lastmod: new Date(),
          priority: 1,
        };
      });
    } else {
    
    
      console.log(productList.data.msg, "sitemap调用错误+productList");
    }

    // 文章详情
    if (newsList.data.code == 200) {
    
    
      let newsArr = newsList.data.rows;
      newsRoutes = newsArr.map((item) => {
    
    
        return {
    
    
          url: `/pressCenter/article?id=${
      
      item.id}`,
          changefred: "daily",
          lastmod: new Date(),
          priority: 1,
        };
      });
    } else {
    
    
      console.log(newsList.data.msg, "sitemap调用错误+newsList");
    }
    // 最后统一将所有组装好的数组合并到总数组中,记住传入合并的数组顺序要跟Promise.all调用接口的顺序一致,否则会出问题
    // 合并后的样子 见下面标注2
    return routes.concat(prodRoutes, newsRoutes);

标注1

// 示例:某一路由对象生成后的样子
   	   {
    
    
         url: `/pressCenter/article?id=1`,
         changefred: "daily",
         lastmod: new Date(),
         priority: 1,
       }

标注2
route.concat es un método de fusión de matrices, podemos usarlo para fusionar objetos de sitio estáticos y dinámicos en una matriz de enrutamiento, y el mapa del sitio eventualmente usará esta matriz para procesarla en datos reales de sitemap.xml.

[
    {
    
    
       url: `/`,
       changefred: "daily",
       lastmod: new Date(),
       priority: 1,
   },
   {
    
    
       url: `/product/twoPage/threePage?id=1`,
       changefred: "daily",
       lastmod: new Date(),
       priority: 1,
   },
   {
    
    
       url: `/pressCenter/article?id=1`,
       changefred: "daily",
       lastmod: new Date(),
       priority: 1,
   },
   ...
]

4. Introduzca y utilice el archivo de configuración sitemap.js globalmente en nuxt.config.js

// nuxt.config.js
import sitemap from "./static/sitemap";
// sitemap跟modules是同级的,一般放在modules的上面或者下面
 modules: [
    "@nuxtjs/sitemap"
  ],
sitemap: sitemap,

5. Código completo de sitemap.js

import axios from "axios";  //
const sitemap = {
    
    
  path: "/sitemap.xml", //生成的文件路径
  hostname: "http://www.baidu.com/", //网站的网址
  cacheTime: 1000 * 60 * 60 * 24, //一天的更新频率,只在generate:false有用
  gzip: true, //用gzip压缩优化生成的 sitemap.xml  文件 
  generate: false,
  exclude: [], //排除不要的页面,这里的路径是相对于hostname
  defaults: {
    
    
    changefred: "always",
    lastmod: new Date(),
  },
  routes: async () => {
    
    
    // 静态路由
    let routes = [
      {
    
    
        url: `/`,
        changefred: "daily",
        lastmod: new Date(),
        priority: 1,
      },
      {
    
    
        url: `/pressCenter`,
        changefred: "daily",
        lastmod: new Date(),
        priority: 0.9,
      },
    ];

    // 以下都是动态路由
    let axiosUrl = "你的接口请求前缀";  // 示例 "http://www.baidu.com/api/"
    let prodRoutes = [];
    let newsRoutes = [];

    // 并发调接口
    let [productList, newsList] = await Promise.all([
      axios.get(axiosUrl + "product/list"),
      axios.get(axiosUrl + "news/list"),
    ]);

    // 商品详情
    if (productList.data.code == 200) {
    
    
      let proList = productList.data.rows;
      prodRoutes = proList.map((item) => {
    
    
        return {
    
    
          url: `/product/twoPage/threePage?id=${
      
      item.id}`,
          changefred: "daily",
          lastmod: new Date(),
          priority: 1,
        };
      });
    } else {
    
    
      console.log(productList.data.msg, "sitemap调用错误+productList");
    }

    // 文章详情
    if (newsList.data.code == 200) {
    
    
      let newsArr = newsList.data.rows;
      newsRoutes = newsArr.map((item) => {
    
    
        return {
    
    
          url: `/pressCenter/article?id=${
      
      item.id}`,
          changefred: "daily",
          lastmod: new Date(),
          priority: 1,
        };
      });
    } else {
    
    
      console.log(newsList.data.msg, "sitemap调用错误+newsList");
    }

    return routes.concat(prodRoutes, newsRoutes);
  },
};
export default sitemap;

6. Cómo generar el archivo sitemap.xml

1. Inicie el proyecto nuxt
  • Abra el archivo estático -> robots.txt. Si no hay un archivo robots.txt, ingresaré al tutorial y agregaré dos atributos de mapa del sitio, una dirección de proyecto local y una dirección en línea. Al generar el archivo sitemap.xml, debe comentar la dirección en línea con el signo # y luego colocar el enlace local como http://192.168.1.193/sitemap.xml en el navegador para visitar, 193 corresponde a su IP del host.
User-agent: *
Disallow:
# Sitemap: http://www.baidu.com/sitemap.xml
Sitemap: http://192.168.1.193/sitemap.xml
2. Se ve así después de acceder, y luego CTRL + S para guardar sitemap.xml en el escritorio; hasta ahora, los pasos de generación de sitemap.xml han terminado.

<loc>标签中的网站地址是根据sitemap.js中的hostname设置的值
inserte la descripción de la imagen aquí

3. Una vez completada la generación, cambie el mapa del sitio de robots.txt a una dirección en línea.
User-agent: *
Disallow:
Sitemap: http://www.baidu.com/sitemap.xml
# Sitemap: http://192.168.1.193/sitemap.xml
4. Nuxt front-end npm run build:prod crea un paquete para el back-end

7. Cómo subir sitemap.xml al servidor

这里以服务器Nginx为例

1. Subir aquí

inserte la descripción de la imagen aquí

2. Configure la ruta de acceso de sitemap.xml en el archivo de configuración de Nginx.

inserte la descripción de la imagen aquí
Después de configurar la recarga de Nginx, vuelva a cargarlo y luego abra la página web en su URL/sitemap.xml para ver si puede acceder a ella. Si puede, significa que Baidu ha incluido su sitio web con éxito.

8. Digresión

Este artículo se acaba de escribir recientemente y algunos errores tipográficos o ciertas expresiones de oraciones se corregirán en el seguimiento.

Supongo que te gusta

Origin blog.csdn.net/Steven_Son/article/details/127922593
Recomendado
Clasificación