Idea: ERB helper to easy enabling HMR
renchap opened this issue · 7 comments
I have been thinking on how to improve our HMR support and have a way to toggle it globally while reducing the boilerplate.
The best idea I have is to provide a Ruby helper and have people use packs/application.js.erb
.
The interface would look like:
# packs/application.js.erb
<%= register_react_components {
Hello: 'components/Hello',
App: 'components/App',
} %>
Which will generate the following JS code:
import Hello from 'components/Hello'
WebpackerReact.register(Hello)
if (module.hot) {
module.hot.accept(
'components/Hello',
() => WebpackerReact.renderOnHMR(Hello)
)
}
import App from 'components/App'
WebpackerReact.register(App)
if (module.hot) {
module.hot.accept(
'components/App',
() => WebpackerReact.renderOnHMR(App)
)
}
We can then have a Rails config flag to enable / disable HMR, as well as a register_react_components
param to override it. This will also allow to only enable HMR (and lot relevant code) depending on Rails environment.
Webpacker enables ERB processing in Webpack config by default, so this should work out of the box. I dont fully like the need to have the users move their packs to ERB, but it looks like much more flexible than any other solutions I thought about.
Again, why this javascript can't be part of the JS library?
Yes, you can find more context here: renchap/webpacker-react-example#2 (comment)
We havent been able to find documentation on the internals for HMR in Webpack 2. I would have preferred a 100% JS solution where you only have to register your component, but it does not seem possible due to the way HMR works.
@renchap i like the idea, alternative would be a babel plugin, but the .erb solution is just much simpler.
@sevos do you think we can have a simpler pure-JS solution? I tried again to look at how to make this work with Webpack & hot-reloading, without any results.
I will work on implementing the ERB otherwise.
First, what do you think if we define the requirements explicitly? Like a real ticket at a software product dev. What is the exact challenge?
Sure. I have several goals:
- avoid the need for boilerplate to be added for HMR (in the common cases at least)
- be able to easily enable / disable HMR depending on a Rails config option. Ideally I would like for new users to try it out just by flipping this option and running
./bin/webpack-dev-server --hot
in place ofwebpack-watcher
- completely disable all HMR-related code in production (smaller pack)