gaearon / ama

Ask me anything!
222 stars 5 forks source link

react-fast-refresh from scratch #166

Open nojaf opened 2 years ago

nojaf commented 2 years ago

Hello Dan,

After reading https://github.com/facebook/react/issues/16604#issuecomment-528663101, I'm interested in what it would take to get this working without an existing bundler.

I'm asking in regards to the https://github.com/AngelMunoz/Perla project. This is a .NET devServer that replace imports from package to CDN URLs (from Skypack). Perla will create an import map so the browser understands everything but that is about it. Basically in this setup, I have two givens:

Currently, the full page is reloaded when the web worker receives a changed event. I'm wondering if it is possible to initiate the react refresh.

Imagine I have an app.js with:

import React from 'https://cdn.skypack.dev/react';

function App() {
    return React.createElement('div', null, `App component`);
}

export default App;

At some point, I know it was changed and wish to refresh it.

So my main question here is: can I pull this off? The original guide speaks about:

try {

  // !!!
  // ...ACTUAL MODULE SOURCE CODE...
  // !!!
  ==> I cannot just put the source code here, the browser doesn't like the `import React from 'https://cdn.skypack.dev/react';` part
           The import and export should be top-level I guess?

} finally {
  window.$RefreshReg$ = prevRefreshReg;
  window.$RefreshSig$ = prevRefreshSig;
}

If the component changed, how exactly do I reload it in the browser? Can I just dynamically import it again?

And lastly, I believe I'll need to call let enqueueUpdate = debounce(runtime.performReactRefresh, 30); to trigger the refresh.

Thoughts?