9
5

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.

webpack-dev-server使用時にSPAが操作するhistoryのpathに対して同じhtmlを返す

Last updated at Posted at 2020-01-09

TL;DR

SPAがhistoryに送ったことで形成される、物理的に存在しないpathでもwebpack-dev-serverでSPA利用を続けたい。
configでかいけつできた。

本論

問題点

webpack-dev-serverでSPAをloadするhtmlをserveしている場合、当然outputに指定した物理pathではdocumentが返却される。
一方でSPAでhistory.pushしたpathでdocumentごとリロードしてしまうと、当然そのpathに対応するhtmlはないので404になってしまう。

間違ってリロードすると元のpathにアクセスしてSPA操作しなおさないと同じ状態にもどれなくて非常にストレスなのでどうにかしたい。

解決策

wepback.devServer.historyApiFallbackを使う。

記述例

  • index.htmlをSPAのマウントに使用
  • rootは/ (= /index.html)
  • /以降のpathに対する全リクエストに対して、index.htmlを返す
historyApiFallback: {
  rewrites: [{ from: /^\/*/, to: '/index.html' }],
},

感想

便利。もっと早くやっとけばよかった。
記事タイトルの日本語がむずかしい。

ちなみに

webpackでbuildで生成したものたちはnetlifyにデプロイしている。
netlify側ではリダイレクトの設定をしている。
リダイレクト設定の記事

9
5
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
9
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?