2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Next.js + Netlifyで作ったサイトにsitemap.xmlを設置する

Posted at

概要

Next.js + Netlifyで作ったサイトにsitemap.xmlを設置しようとしたら多少ハマったのでメモ。

環境

next.js 9.5.2

コード

最終的に動いたコードが以下。
今回加筆したのは2ファイルのみで、とてもシンプルだった。
./postexport.jsは新しく作成した。

package.json
{
  "name": "サイト名",
  "version": "1.0.0",
  "scripts": {
    "dev": "next -p 8080",
    "build": "next build",
    "export": "next export",
    "deploy": "npm run build && npm run export",
    "postexport": "node ./postexport.js",   //追記
    "start": "next start -p 8080",
    "type-check": "tsc"
  },
...
}
./postexport.js
const fs = require('fs');

// ROBOTS.txt
const robotsTxt = `User-agent: *
Sitemap: https://〇〇.com/sitemap.xml
Disallow:`;

fs.writeFile('out/robots.txt', robotsTxt, () => {
  console.log('robots.txt saved!');
});

// SITEMAP.XML
const location = "https://〇〇.com/"
let xmlPaths = `<url>
    <loc>${location}</loc>
    <priority>1.0</priority>
  </url>`;

//ページ名の配列
const page_data = [
  "about",
  "member",
  "gallery",
  "privacy",
  "contact",
];

page_data.map((page_path) => {
  const URL = location + page_path;
  xmlPaths += `
    <url>
      <loc>${URL}</loc>
      <priority>0.5</priority>
    </url>
  `;
});

const sitemapXml = `<?xml version="1.0" encoding="UTF-8"?>
  <urlset
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
    xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
    xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"
    xmlns:geo="http://www.google.com/geo/schemas/sitemap/1.0"
    xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"
    xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0"
    xmlns:pagemap="http://www.google.com/schemas/sitemap-pagemap/1.0"
    xmlns:xhtml="http://www.w3.org/1999/xhtml"
    xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"
  >
    ${xmlPaths}
  </urlset>`;

fs.writeFile('out/sitemap.xml', sitemapXml, () => {
  console.log('sitemap.xml saved!');
});

参考

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?