LoginSignup
3

More than 3 years have passed since last update.

【React】Fast Refresh を有効にする

Last updated at Posted at 2020-12-07

以前から react-hot-loader を使って、 HMR (Hot Module Reloading) を行ってきましたが、
ReactFast Refreshというネイティブ機能が提供されましたので、こちに移行します。
今回は webpack を使った場合、具体的にな設定を説明します。

ライブラリインストール

Fast Refresh 機能は、react-refresh を追加でインストール必要です。
webpack使う場合、babel とプラグインもインストール必要がある

Install
yarn add react-refresh
yarn add @babel/core babel-loader @pmmmwh/react-refresh-webpack-plugin -D

設定

意外と設定する場所が少ないが、プラグインなしの場合死ぬほど難しいそうです。

webpack.ts
import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin';

const configs: Configuration = {
  ...
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            // *** ここから ***
            options: { plugins: ['react-refresh/babel'] },
            // *** ここまで ***
          },
          {
            loader: 'ts-loader',
            options: {
              transpileOnly: true,
            },
          },
        ],
      },
    ],
  },
  plugins: [
    ...
    // *** ここから ***
    new ReactRefreshWebpackPlugin(),
    // *** ここまで ***
  ],
  ...
};

試して見る

デモ用ソースは GitHub で公開中です。
https://github.com/wwalpha/react-refresh-typescript-example

DEMO
git clone https://github.com/wwalpha/react-refresh-typescript-example.git
cd react-refresh-typescript-example
yarn install
yarn start

全部5種類コンポーネントがテストできます。

  • Class Default
  • Class Named
  • Function Default
  • Function Named
  • Lazy Component

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
3