Skip to content

mixail-novikov/babel-plugin-transform-react-lazy

Repository files navigation

Description

Restoring Fast Refresh when using React.lazy

Problem

Fast Refresh can't properly handle React.lazy.

Solution

Replace dynamic imports to the regular imports

Benefits

  • restored developer experience with Fast Refresh
  • can catch syntax errors instantly(in comparison, using "dynamic import" the code executes only when it loaded)

Caveats

  • use only in development environment
  • import source must be a regular string

Usage with CRA and customize-cra

  1. Enable Fast Refresh:

  2. Install the plugin

npm install --save-dev babel-plugin-transform-react-lazy
  1. Use the plugin
// config-overrides.js
const { override, addBabelPlugin } = require("customize-cra");
const { addReactRefresh } = require("customize-cra-react-refresh");

module.exports = override(
  addReactRefresh(),
  process.env.NODE_ENV === "development" &&
    addBabelPlugin("transform-react-lazy")
);