【问题标题】:Dynamic sitemap by next-sitemap下一个站点地图的动态站点地图
【发布时间】:2022-02-10 14:51:38
【问题描述】:

我想通过下一个站点地图将 server-sitemap.xml 添加到我的下一个 js 应用程序中, 如果有人能解释我如何在 nextjs 中通过 next-sitemap 添加动态站点地图,我将不胜感激。

import { GetServerSideProps } from "next"
import { getServerSideSitemap,ISitemapField } from "next-sitemap"
const { all_product_get }  = require("../../src/api/guest")
export const  getServerSideProps =  GetServerSideProps async (ctx) => {
let data = [] 
await all_product_get().then(res => {
data : res.data.data
})
const fields :ISitemapField[]  = data.map(item => ({loc :`https://sivanland.com/product/detail/${item._id}`,
lastmod: new Date().toISOString()}))
return getServerSideSitemap(ctx, fields);
};
export default function Site(){}

【问题讨论】:

  • 您尝试了哪些方法,哪些方法不起作用?

标签: reactjs next.js


【解决方案1】:

我自己解决了。

  1. 将 TypeScript 添加到我的项目中:npm i -D typescript
  2. tsconfig.json添加到项目根目录
  3. 在 NextJS 中使用 TypeScript。

tsconfig.json:

{
    "compilerOptions": {
        "allowJs": true,
        "allowSyntheticDefaultImports": true,
        "jsx": "preserve",
        "lib": [
            "dom",
            "es2017"
        ],
        "module": "esnext",
        "moduleResolution": "node",
        "noEmit": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "preserveConstEnums": true,
        "removeComments": false,
        "skipLibCheck": true,
        "sourceMap": true,
        "strict": true,
        "target": "esnext",
        "forceConsistentCasingInFileNames": true,
        "esModuleInterop": true,
        "resolveJsonModule": true,
        "isolatedModules": true,
        "incremental": true
    },
    "exclude": [
        "node_modules"
    ],
    "include": [
        "next-env.d.ts",
        "**/*.ts",
        "**/*.tsx"
    ]
}
  1. 然后我将上面的代码与数据库中的动态数据一起使用:
import { getServerSideSitemap, ISitemapField } from 'next-sitemap'
import { GetServerSideProps } from 'next'

 export const getServerSideProps: GetServerSideProps = async (ctx) => {
// Method to source urls from cms
const response = await fetch('https://newapi.example.com/api/guest/search   /product/all');
let items: any = {}
items = await response.json();

const fields: ISitemapField[] = items.data.map((item: any) => ({
    loc: `https://www.example.com/product/detail/${item._id}`,
    lastmod: new Date().toISOString(),
    changefreq: 'daily',
    priority: '0.7'
}));
return getServerSideSitemap(ctx, fields)
}

export default function Site() { }
  1. 添加文件夹:pages/server-sitemap.xml/index.tsx

  2. 并将上述代码粘贴到 index.tsx

  3. 将站点地图地址添加到 next-sitemap.gonfig.js

additionalSitemaps: [
  'https://example.com/sitemap.xml',
  'https://example.com/server-sitemap.xml'
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    • 2012-12-10
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多