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 5 years have passed since last update.

Gatsby.jsでpages/indexディレクトリを"/"として認識する

Last updated at Posted at 2019-11-01

やりたいことはタイトルそのまんまです

pages/indexディレクトリを作成して、以下のような感じにするとできます。

gatsby-node.jsに以下のonCreatePageに関する挙動を設定してください。

gatsby-node.js
// to avoid making path "/index/" instead of "/" with index directory
// see https://github.com/gatsbyjs/gatsby/issues/7363
exports.onCreatePage = ({ page, actions }) => {
	const { deletePage, createPage } = actions;

	return new Promise(resolve => {
		if (page.componentPath === `${__dirname}/src/pages/index/index.tsx`) {
			deletePage(page);

			// create a new page but with '/' as path
			createPage({
				...page,
				path: '/'
			});
		}
		// if you have any directories or files under the src/pages/index
		else if (page.componentPath.match(`${__dirname}/src/pages/index`)) {
			deletePage(page);
		}
		resolve();
	});
};

page作成時にもしそれがindexディレクトリのindex.tsxだったら削除してパスを"/"としてページを作ります。
pages/index配下に他のファイルがあった場合"/index/any"のような感じでページが作られてしまうので、index配下のファイルは削除するようにしています。

まとめ

pagesディレクトリ配下のファイルはルーティングに専念した方がいいと思うので、ここに書いてある方法を試すより別のディレクトリで同じことをやった方がいいと思います()。

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?