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?

Remix ファイル名ではなくフォルダを使ってURLを指定したい

Last updated at Posted at 2025-03-04

概要

RemixにはURLの指定方法が2つ存在する。

  • ファイル名を.を使って区切りURLの構造を指定
  • フォルダを用いURLの構造を指定

今回「ファイル名を.を使って区切りURLの構造を指定」から「フォルダを用いURLの構造を指定」に変更したところ若干詰まったので記事にする。

前提

.を用いたURLの指定は下記のように実装されている。

app/
└── routes/
    ├── hoge.tsx
    └── hoge.fuga.tsx

ファイルパスとURLの関係をまとめる

ファイルパス URL
app/routes/hoge.tsx /hoge
app/routes/hoge.fuga.tsx /hoge/fuga

この状態で$ npm run devを実行し、ローカル開発環境で/hoge/hoge/fugaにアクセスするとそれぞれ問題なく画面が表示される。

あまり調べずに実装して詰まった方法

フォルダに共通化するということなのであまり調べず下記のようにしてみた。

app/
└── routes/
    └── hoge/
        ├── index.tsx
        └── fuga.tsx

この状態で$ npm run devを実行し、ローカル開発環境で/hogeは表示される。/hoge/fugaは404になる。
その後も下記のパターンを試したが/hogeは表示され、/hoge/fugaは404になる症状は解消しない。

app/
└── routes/
    └── hoge/
        ├── index.tsx
        └── index.fuga.tsx
app/
└── routes/
    └── hoge/
        ├── index.tsx
        └── hoge.fuga.tsx
app/
└── routes/
    └── hoge/
        ├── index.tsx
        └── fuga/
            └── index.tsx

解消した方法

参考文献先の記事や公式ドキュメントを読んだところフォルダ名・ファイル名ともにの指定に誤りがあった。
どうやらフォルダ名で.を用いて階層構造を指定する必要があるらしい。
うまくいった構造を下記に記載する。

app/
└── routes/
    └── hoge._index/
        └── index.tsx
    └── hoge.fuga/
        └── index.tsx

この場合のファイルパスとURLの関係をまとめる

ファイルパス URL
app/routes/hoge._index/index.tsx /hoge
app/routes/hoge.fuga/index.tsx /hoge/fuga

なぜイケてない方法でも/hogeは表示されたのかの予想

確証に至ってない予想だが

フォルダ名の._indexは省略可能である可能性が高い。

app/
└── routes/
    └── hoge._index/
        └── index.tsx

app/
└── routes/
    └── hoge/
        └── index.tsx

は同様の意味を持つのでは無いだろうか?
その裏付けとして下記のように定義しても問題なく/hoge/hoge/fugaも表示出来た。

app/
└── routes/
    └── hoge/
        └── index.tsx
    └── hoge.fuga/
        └── index.tsx

ちなみに下記は/hoge/fugaが表示出来なかった。

app/
└── routes/
    └── hoge/
        ├── index.tsx
        └── .fuga/
            └── index.tsx

まとめ

ファイル名とフォルダを使ったURL指定の方法を表でまとめると下記のようになった。

ファイル名を使った場合
のファイルパス
フォルダを使った場合
のファイルパス
URL
app/routes/hoge.tsx app/routes/hoge._index/index.tsx /hoge
app/routes/hoge.fuga.tsx app/routes/hoge.fuga/index.tsx /hoge/fuga

まだなれていないのでファイルベースルーティングに苦戦しているが、慣れたら確実にわかりやすいと感じた。

参考文献

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?