LoginSignup
12
8

More than 5 years have passed since last update.

react-routerとbrowser-syncを利用して快適に開発するちょっとした設定

Last updated at Posted at 2015-12-29

react-routerを使いSPAの構成でcreateBrowserHistoryを設定し、
browser-syncのserverを起動して開発しているとreloadをしたタイミングで、

cannot get XXX

と怒られてしまいます。

これはhistoryによって構築された擬似的なURLで再ロードした場合に、
対象のファイルが存在しておらずhtmlの取得自体に失敗してエラーになっているので正しい動作と言えます。

この動きをエラーとさせずいい感じに動かすためには、
browser-syncのmiddlewareを以下の様に設定する事で簡単に対応可能です。

  // ES6
  const index_file = fs.readFileSync(path.join(__dirname, "./public/index.html"), "UTF-8");
  browserSync.init({
    server: {
      baseDir: ".",
      // 存在しないURLを実行された場合でもindex.htmlの内容を描画する(F5などの対応)
      // CSSなども同一パスであればその辺は微調整が必要
      middleware: [(req, res, next) => /^\/(public)\/.+/.test(req.url) ?
          res.end(index_file) : next()
      ]
    }
  });

大体これでうまくいっている感じな気がします。

12
8
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
12
8