14
3

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.

Create React Appで作ったReactアプリケーションを相対パスへデプロイする

Last updated at Posted at 2020-12-03

同じ内容をZennにも投稿しました。


概要

Create React Appで作ったReactアプリケーションをhttps://example.com/のようなルートではなく、https://example.com/foobar/のような相対パスへデプロイする方法を書きます。

相対パスへデプロイできるようにする方法

方法はCreate React Appの公式ドキュメント、DeploymentのBuilding for Relative Pathsというセクションに書かれています。

まずpackage.json"homepage": "/foobar/"を追加します。
公式ドキュメントではhttp://mywebsite.com/relativepathというような絶対URIが書かれていますが、/から始まるパスでも大丈夫です。

それから、React Rotuerを使用している場合はBrowserRouterbasename属性を設定します。

<BrowserRouter basename="/foobar/">

basename属性さえ設定しておけば、Link要素のto属性やRoute要素のpath属性は相対パスを気にすることなく設定できます。

どうやって実現しているの?

package.jsonからhomepageを読み取っているのはpaths.jsです。

読み取った値はwebpack.config.jsWebpackのPublic Pathに渡されています。

あとはWebpackがjsファイルやcssファイルを設定した相対パスから読み込むようにビルドしてくれます。

なお、React Routerの方はまだソースコードを読んでいないので省略します。

コード例

14
3
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
14
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?