1
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.

Gatsby のURLに含まれる スラッシュ/ や index を消したい

Last updated at Posted at 2020-11-09

元記事:genkitech.net

Gatsbyのプロジェクトによっては、記事をディレクトリに分割してindex.mdを作成していると、URLが以下のようになる事があります。

http://localhost:8000/blog-title/
http://localhost:8000/blog-title/index/

これを

http://localhost:8000/blog-title

にする方法です。

コードを編集

gatsby-node.jsにあり、slugを生成しているところを書き換えます。

この部分はホットリロードに対応していないので、変更後リビルドしてください。

  switch (node.internal.type) {
    case 'MarkdownRemark': {
      const { permalink, layout, primaryTag } = node.frontmatter;
      const { relativePath } = getNode(node.parent);

      let slug = permalink;


      if (!slug) {

        // ↓↓↓↓↓↓↓↓↓ここを書き換え↓↓↓↓↓↓↓↓↓↓
        // slug = `/${relativePath.replace('.md', '')}/`;

        slug = `/${relativePath.replace('.md', '').replace('/index', '')}`;
      }

      // Used to generate URL to view this content.
      createNodeField({
        node,
        name: 'slug',
        value: slug || '',
      });

      // Used to determine a page layout.
      createNodeField({
        node,
        name: 'layout',
        value: layout || '',
      });

      createNodeField({
        node,
        name: 'primaryTag',
        value: primaryTag || '',
      });
    }
  }
};

1
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
1
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?