andrefelipe / vite-php-setup

Example on how to run Vite on traditional PHP sites
https://github.com/vitejs/vite
358 stars 52 forks source link

HMR / Reload for vanilla js setup #1

Closed arnoson closed 3 years ago

arnoson commented 3 years ago

Thank you so much for sharing your setup, it works great! I was wondering if it would also be possible to use this in an vanilla js setup without vue? I get it running but the javascript files aren't updated. I guess I somehow have to build HMR for vanilla js files myself but I'm not sure how to do this.

andrefelipe commented 3 years ago

Good question, I tested here and HMR for vanilla JS just doesn't work. And I am not sure why.

I also tested on a plain Vite project from https://github.com/vitejs/create-vite-app and it does work for vanilla JS. When changing index.js the browser refreshes.

Maybe the latests commits on Vite will help us, they have to do with a PHP entry file: https://github.com/vitejs/vite/commits/master

Who knows our setup will get simplified too.

Will post here if I find a solution.

arnoson commented 3 years ago

I tested it a bit further, and everything seems to work except to top level index.js changes. But if my index.js imports a module and the module changes, my site refreshes as expected. So one workaround would be to move all code from the index.js into a module. Another thing I noticed is: if I have an index.html in my vite folder that mirrors the scripts that I use in my index.php than also the toplevel changes in my index.js trigger page refresh. So somehow vite needs the index.html although I don't use it. But yes, maybe in the future the whole setup will get even easier when php files will be allowed as entrypoints!

arnoson commented 3 years ago

I described this behavior in more detail here

andrefelipe commented 3 years ago

Great! Thanks for the feedback.

arnoson commented 3 years ago

As a workaround I created a vite live reload plugin. Now my config looks something like this

// vite.config.js
import liveReload from 'vite-plugin-live-reload'

export default {
  // ...
  plugins: [
    liveReload('index.js'),
  ]
}

The plugin also has the benefit, that I can also watch my php files and my site gets reloaded everytime I change something.

andrefelipe commented 3 years ago

Great!! I will use that already in a project.

arnoson commented 3 years ago

I just released a small update with typescript support and the watcher is now relative to vite's root folder which seemed to be more consinstent :)

arnoson commented 3 years ago

With vite 2 this issue has been resolved (:

andrefelipe commented 3 years ago

Great! Thanks for cleaning up the issue.