JorgenVatle/meteor-vite

Error: @vitejs/plugin-react can't detect preamble.

Closed this issue · 6 comments

Error: @vitejs/plugin-react can't detect preamble.
The errors happen as soon as we run the meteor project.

I would love to see it working with React ❤️

I created a repo to reproduce the issue: https://github.com/henriquealbert/meteor-vite-react
Screenshot 2023-09-08 at 09 05 15

Thank you for creating the repo there! 🙌

I'll go through and see what I can do about it in a bit.

Related: #26

Just a quick update on this, adding the following snippet to the Meteor main.html file, explicitly importing the React fast refresh module as suggested in #26 from Vite instead of the the Meteor web server seems to resolve the issue on my end.

By default the Vite server created by Meteor Vite is available at http://localhost:5173/

<script type="module">
import RefreshRuntime from "http://localhost:5173/@react-refresh" // Local Vite server created by Meteor-Vite.
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>

Though, as the above snippet would be shipped into production if you just add it to your Meteor HTML file. Instead, we can take advantage of some of the internals for Meteor and Meteor-Vite to build a reliable snippet on demand when Meteor is running in development;

// server/main.js
import { WebAppInternals } from 'meteor/webapp';
import { getConfig } from 'meteor/jorgenvatle:vite-bundler/loading/vite-connection-handler';

if (Meteor.isDevelopment) {
  WebAppInternals.registerBoilerplateDataCallback('react-preamble', (request, data) => {
    const { host, port } = getConfig();
    data.dynamicHead = data.dynamicHead || '';
    data.dynamicHead += `
<script type="module">
  import RefreshRuntime from "http://${host}:${port}/@react-refresh"
  RefreshRuntime.injectIntoGlobalHook(window)
  window.$RefreshReg$ = () => {}
  window.$RefreshSig$ = () => (type) => type
  window.__vite_plugin_react_preamble_installed__ = true
</script>
    `
  })
}

@henriquealbert I've shipped an example React app that should be working. Do note that the Vite config includes a custom plugin that forces Vite to use the React version bundled by Meteor in case you're using any of the Meteor React packages.

Let me know how it goes. 🙏
React Example

It looks good! I'll ask to of our team members to test it. Thank you @JorgenVatle 🙏🏻

It worked perfectly! Great work @JorgenVatle 👏🏻