LoginSignup
2

More than 5 years have passed since last update.

After.js で SSR / Code Splitting on react-router

Last updated at Posted at 2018-04-12

after.js とは、「next.js meets react-router.」 です。以上。

after.js、 おそらく本来のプロジェクト名は razzle だと思うんですが、 next.js に対抗して razzle エコシステムをかき集めたものを after.js と呼んでるみたいです。

ルーティングのコード例

import React from 'react'
import Layout from './components/Layout'
import { asyncComponent } from '@jaredpalmer/after'

const loadingPlaceholderWithLayout = <Layout>Loading...</Layout>

export default [
  {
    path: '/',
    exact: true,
    component: asyncComponent({
      loader: () => import('./pages/Home'), // required
      Placeholder: () => loadingPlaceholderWithLayout
    })
  },
  {
    path: '/about',
    exact: true,
    component: asyncComponent({
      loader: () => import('./pages/About'), // required
      Placeholder: () => loadingPlaceholderWithLayout
    })
  },
  {
    path: '/detail/:id',
    exact: false,
    component: asyncComponent({
      loader: () => import('./pages/Detail'), // required
      Placeholder: () => loadingPlaceholderWithLayout
    })
  }
]

クライアント遷移時はルート要素に placeholder を刺した上で非同期ローディングを開始するので、 それぞれの要素の中でも使ってる Layout 要素 を一旦展開しておかないと、かなりガクガクします

next みたいに pages 以下のファイルパスが暗黙にURLになったりはしません

next.js と同じ点

  • static async getInitialProps() {...} による非同期SSR
  • エントリポイントごとの Code Splitting
  • .babelrc を隠蔽
  • webpack を隠蔽

サーバーは src/index 、クライアントは src/client がエントリポイントです。他はなんか適当に razzle のヘルパを使うと next.js みたいに動きます。そういう風になってるというドキュメントが見つけられなかったけど自分が試した限りはそう動きました。

規約が少ない分、自由度が高いんですが、自分でコードを書く量は増えます。

pages/index.js に ReactComponent 定義を置くと起動する next.js の開発体験には全く及びませんが、結局 next も カスタムサーバーを起動する server.js とか pages/_document.js とか書かなかったことないし、むしろ最初から剥き出しになってる方が、最終的な安心感はありますね。

next.js との違い

  • react-router
    • react-router 剥き出しなので他のライブラリと連携しやすい
    • next.js は独自ルーターなんで他のライブラリとの連携やハックが辛かった
  • サーバーモードのみで static export なし
    • 必ず node アプリケーションとしてデプロイする必要があり
    • サーバーで受けてルーティングするので、URLの自由度は高い(というか next の URL表現が貧弱すぎる…)

全体的にexpress と react-router 剥き出しです。そのまま使う。

どっちを選ぶか

  • 静的エクスポートしたい => next.js
  • SSR とかコードスプリッティングを自分で書きたくない => どっちでもいい
  • react-router に慣れてる/好き => next.js

静的エクスポートするかどうか決まってるなら、あとは自分が webpack react-router エコシステムに強いか、next.js に巻かれたいかで選ぶと良いと思います。要は node に強いかどうかです。

書き味

どんなコードになるかはサンプルプロジェクトを作りました。 https://github.com/mizchi/razzle-project-example
now に一発でデプロイ出来るようにしてます。

公式の README が非常に読みづらいというか、動かないコードや暗黙の事前条件が必要なものを解説無しで平気で書いてるので、ドキュメントから気持ちを察するのに時間がかかりました。

最後に

ここまで書いておいて何ですが、僕は react-router 好きじゃなくて、任意の要件に対してハックできるポイントを調査した感じでした。終わり。

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
2