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

React-Routerでサブディレクトリに配置

Posted at

サブディレクトリにビルドしたい

例えば記事サイトのドメインがあるとして、
/article以下にReactのプロジェクトを置きたいと思った時

普通にビルドして配置すると・・・

○○.chunk.jsなどの向き先が全部ドメイン直下だったり、
Linkで遷移しようとしたら、おかしなページに行ってしまったり。

解決方法は色々出てくる

basename='/article'入れるらしいけど、ドコに書けばいいんだ?
webpack.config.jsoutput:の中かしら?
cross-envbuildの後ろに書くのかしら?

ネットで調べるとサブディレクトリに置く方法は色々あり、どれが正解か分からないッス。
Switchの中に書いてみたり、Routeのタグに書いてみたり、
Linkの中身のURLを書き換えてみたり、と小一時間迷ってしまいます。

結論:<App/>を囲んでるhistoryの書き方を変える

環境によって違うかもですが、一番上の階層にあるファイルで
historyを読み込んでる所があると思います(ないかもですが)
そこを書き換えます。

yarn add history
app.js
- //import history from 'utils/history';
+ import createBrowserHistory from 'history/createBrowserHistory';
app.js
+ const history = createBrowserHistory({ basename: '/article' }); //←ココに追加する
const render = () => {
  ReactDOM.render(
    <Provider store={store}>
      <ConnectedRouter history={history}> //←ココに「history」がある、と思う。
        <App />
      </ConnectedRouter>
    </Provider>,

私の場合はこれで解決しました。
create-react-appの場合は、npmスクリプトに書くように書いてあったので、
そっちの場合はちょっとよくわからないです。

参考資料を見る限りだと、RouterBrowserRouterでも動きそう。
reduxがある場合<Provider><App/>でサンドイッチにする感じ。

以上です。

参考資料

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