Skip to content

theKashey/react-hot-loader

 
 

Repository files navigation

React Hot Loader

Build Status version MIT License

PRs Welcome Chat

Watch on GitHub Star on GitHub

Tweak React components in real time ⚛️⚡️

Watch Dan Abramov's talk on Hot Reloading with Time Travel.

Install

npm install --save react-hot-loader

Note: You can safely install react-hot-loader as a regular dependency instead of a dev dependency as it automatically ensures it is not executed in production and the footprint is minimal.

Getting started

  1. Add react-hot-loader/babel to your .babelrc:
// .babelrc
{
  "plugins": ["react-hot-loader/babel"]
}
  1. Enable Hot Module Replacement in Webpack

  2. Add react-hot-loader/patch at the top of the entry section (except polyfills) of your Webpack config:

// webpack.config.js
module.exports = {
  entry: [
    'babel-polyfill',
    'react-hot-loader/patch',
    './main.js'
  ]
}

Note: Make sure to set the output.publicPath property to "/" as well. Otherwise hot reloading won't work as expected for nested routes.

  1. Wrap your application into <AppContainer>, all children of <AppContainer> will be reloaded when a change occurs:
// main.js
import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import App from './containers/App'

const render = Component => {
  ReactDOM.render(
    <AppContainer>
      <Component />
    </AppContainer>,
    document.getElementById('root'),
  )
}

render(App)

// Webpack Hot Module Replacement API
if (module.hot) {
  module.hot.accept('./containers/App', () => { render(App) })
}

Note: To make this work, you'll need to opt out of Babel transpiling ES2015 modules by changing the Babel ES2015 preset to be ["es2015", { "modules": false }]

Using Webpack loader instead of Babel plugin

You may not use Babel in your project, React Hot Loader provides a Webpack loader with limited support. If you want to use it, you can add it in your Webpack config. If you use Babel, you don't need to add this loader.

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: ['react-hot-loader/webpack']
      }
    ]
  }
}

Migrating from create-react-app

  • Run npm run eject

  • Install React Hot Loader (npm install --save-dev react-hot-loader)

  • In config/webpack.config.dev.js:

    1. Add 'react-hot-loader/patch' to entry array (anywhere before paths.appIndexJs). It should now look like (excluding comments):
      entry: [
        'react-hot-loader/patch',
        require.resolve('react-dev-utils/webpackHotDevClient'),
        require.resolve('./polyfills'),
        paths.appIndexJs
      ]
    1. Add 'react-hot-loader/babel' to Babel loader configuration. The loader should now look like:
      // Process JS with Babel.
      {
        test: /\.(js|jsx)$/,
        include: paths.appSrc,
        loader: require.resolve('babel-loader'),
        options: {
    
          // This is a feature of `babel-loader` for webpack (not Babel itself).
          // It enables caching results in ./node_modules/.cache/babel-loader/
          // directory for faster rebuilds.
          cacheDirectory: true,
          plugins: [
            'react-hot-loader/babel'
          ]
        },
      },
  • Add AppContainer to src/index.js (see step 4 of Getting Started).

TypeScript

When using TypeScript, Babel is not required, so your config should look like (demo):

{
  test: /\.tsx?$/,
  loaders: ['react-hot-loader/webpack', 'ts-loader'] // (or awesome-typescript-loader)
}

Source Maps

If you use devtool: 'source-map' (or its equivalent), source maps will be emitted to hide hot reloading code.

Source maps slow down your project. Use devtool: 'eval' for best build performance.

Hot reloading code is just one line in the beginning and one line in the end of each module so you might not need source maps at all.

React Native

React Native supports hot reloading natively as of version 0.22.

Adding a custom error reporter

The previously used Redbox for React Hot Loader has known limitations due to sourcemaps and it's no longer a default catcher. Errors are great to clearly see rendering issues, and avoiding an uncaught error from breaking your app. But there are some advantages to a thrown error in the console too, like filename resolution via sourcemaps, and click-to-open. To get the Redbox back, and have the best of both worlds, modify your app entry point as follows:

import Redbox from 'redbox-react';

const CustomErrorReporter = ({ error }) => <Redbox error={ error } />;

CustomErrorReporter.propTypes = {
  error: React.PropTypes.instanceOf(Error).isRequired
};

render((
  <AppContainer errorReporter={ CustomErrorReporter }>
    <AppRoot />
  </AppContainer>
), document.getElementById('react-root'));

You'll also need to npm install --save-dev redbox-react.

Disable warnings

React Hot Loader will by default emit a warning for components not accepted by the Hot Loader. If you want to disable these warnings, you can pass a warnings prop with the value false to AppContainer.

<AppContainer warnings={false}>
  ...
</AppContainer>

Starter Kit

Provided by collaborators:

Provided by community:

Known limitations

Components not replaced

  • React Hot Loader can't replace any Component, only registered ones.
    • when using webpack loader - only module exports are registered.
    • when using babel plugin - only top level variables are registered.
    • when React Hot Loader can't replace Component, an error message will be displayed.

Code Splitting

If you want to use Webpack code splitting via require.ensure, you'll need to add an additional module.hot.accept callback within the require.ensure block, like this:

require.ensure([], (require) => {
  if (module.hot) {
    module.hot.accept('../components/App', () => {
      loadComponent(require('../components/App').default);
    })
  }
  loadComponent(require('../components/App').default);
});

Note that if you're using React Router (pre-4.0), this will only work with getChildRoutes, but not getComponent, since getComponent's callback will only load a component once.

Also, if you're using the Webpack 2 beta, you can use System.import without extra module.hot.accept calls, although there are still a few issues with it.

Checking Element types

Because React Hot Loader creates proxied versions of your components, comparing reference types of elements won't work:

const element = <Component />;
console.log(element.type === Component); // false

One workaround is to create an element (that will have the type of the proxied component):

const ComponentType = (<Component />).type;
const element = <Component />;
console.log(element.type === ComponentType); // true

You can also set a property on the component class:

const Widget = () => <div>hi</div>;
Widget.isWidgetType = true;
console.log(<Widget />.type.isWidgetType); // true

Reassigning Components

React Hot Loader will only try to reload the original component reference, so if you reassign it to another variable like this:

let App = () => (<div>hello</div>);
App = connect()(App);
export default App;

React Hot Loader won't reload it. Instead, you'll need to define it once:

const App = () => (<div>hello</div>);
export default connect()(App);

Decorators

Components that are decorated (using something like @autobind) currently do not retain state when being hot-reloaded. (see #279)

Troubleshooting

If it doesn't work, in 99% cases it's a configuration issue. A missing option, a wrong path or port. Webpack is very strict about configuration, and the best way to find out what's wrong is to compare your project to an already working setup, such as React Hot Boilerplate, bit by bit.

If something doesn't work, in 99% cases it's an issue with your code - Component doesn't got registered, due to HOC or Decorator around it, which making it invisible to Babel plugin, or Webpack loader.

We're also gathering Troubleshooting Recipes so send a PR if you have a lesson to share!

License

MIT

About

Tweak React components in real time.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%