preactjs / preset-vite

Preset for using Preact with the vite bundler
https://npm.im/@preact/preset-vite
MIT License
262 stars 27 forks source link

Hotreloading doesn't work with lowercase and/or .mjs entrypoint #128

Closed Siilwyn closed 5 months ago

Siilwyn commented 5 months ago

First of all, I'm not sure if this is the correct place or whether this is more prefresh related... Also Preact is truly awesome!

Writing a small webapp using the latest vite and preact versions and I recently figured out why HMR was not working. Fixed it by changing my entrypoint function name from app to App and renaming the file it resides in from app.mjs to app.js. It seems the combination of these two is needed, applying either alone doesn't fix HMR.

Basically:

--- a/src/app.mjs
+++ b/src/app.js

-export default function app() {
+export default function App() {

--- a/src/client.js
+++ b/src/client.js

 import { render, h } from 'preact';
-import app from './app.mjs';
+import App from './app.js';

-render(h(app), document.body);
+render(h(App), document.body);

I hope this is enough information, let me know if I can help out in any way in debugging this.

rschristian commented 5 months ago

Capital letters are needed to distinguish components, yes. This goes for React and Preact.

I think we're missing .mjs in the preset, so Prefresh isn't instructed to transform it.

Siilwyn commented 5 months ago

@rschristian ah interesting, wouldn't changes in other lowercase components fail in that case? All other components are lowercased and have working HMR as long as the entrypoint is in uppercase.

rschristian commented 5 months ago

Hm, not sure, but you definitely shouldn't be using components that start with a lowercase letter. From Prefresh's docs:

Recognition

We need to be able to recognise your components, this means that components should start with a capital letter and hook should start with use followed by a capital letter. This allows the Babel plugin to effectively recognise these.

preactjs/prefresh#recognition

Edit: Both Prefresh & our preset here need fixes, will PR accordingly shortly.

Siilwyn commented 5 months ago

Thanks for the quick reply & fix! :tada:

rschristian commented 5 months ago

No problem, thanks for taking the time to raise an issue!

It's pretty late here so I'll have to make a release for our Vite preset tomorrow -- hopefully it's a quick task w/ patch-package or the like if you need this in the meantime.

Edit: Sorry, I'm going to wait to see if #130 needs a fix too