Can I edit React components without restarting the browser?

If React offers DOM negotiation, is it possible to dynamically reload the component code and re-display it after editing it?

I am looking for a solution that allows me to edit a JSX file, save it and have the component update itself in the browser without reloading the page, unmounting or losing state.

Ideally, this should work without browser plugins.

+6
source share
2 answers

You can use react-hot-loader , a Webpack dropdown that allows live editing of React components in your projects. No browser plugins or IDE hooks are required.

He marries Webpack Hot Module Replacement (HMR) using React.

You can use this if:

  • Your React components do not have unpleasant side effects;
  • You want to switch to Webpack for modules (it’s easy to switch, see the passage );
  • You have a couple of hours (minutes if you are already using Webpack).

How it works:

There is a demo video , an explanatory blog entry and Launch an interactive editing app quiz .

And all this is vanilla js.

+11
source

You can, and I created a sample project that demonstrates how to create these features for myself using ES5 and RequireJS - it works with React, as well as with Backbone - maybe it works with Angular and Ember, etc., if you use AMD and RequireJS modules.

Here is all the information: https://medium.com/@the1mills/hot-reloading-with-react-requirejs-7b2aa6cb06e1

The main steps are:

  • gulp.js watchers listen to file system changes

  • The socket.io server in gulpfile sends a message to all browsers with the path to the file that changed

  • the client removes the cache representing this file / module and re-requires it (using AJAX to pull it out of the server file system)

  • the front-end application is configured / designed to re-evaluate all the links to the modules that it wants hot-reload, in this case, only JS views, templates and CSS available for hot rebooting - the router, controllers, data warehouses are not yet configured. I suspect that all files can be reloaded, except when there is data storage.

Here you can see an example project: https://github.com/ORESoftware/hr4R

but I recommend reading the article above first.

This is an easier hot reload implementation than using Babel / ES6 and React-Hot-Loader.

Webpack was not primarily designed for hot reloading - if it were, hot reloading would no longer be an experimental feature, and would not use polling to see that the file system is different, what it is currently doing (see mine article).

The RequireJS / AMD specification was basically made for a hot reload if you think about it.

0
source

Source: https://habr.com/ru/post/972798/


All Articles