-
I've occasionally run into an issue with Vite where I will add a reference to a class defined in my main script (main.js which is loaded from my index.html) in a script that main.js also depends on. index.html is <!DOCTYPE html>
<title>VITE TEST</title>
<script type="module" src="main.js"></script> main.js could be something like: //@ts-check
import { B } from "./file2.js";
export class A {
constructor() {
this.b = new B();
this.b.fetch(this);
}
} while file2 will be something like: //@ts-check
import { A } from "./main.js";
export class B {
fetch(a) {
console.log('fetching',a);
if (a instanceof A) {
console.log('a is A');
}
}
} While this is perfectly legal JavaScript, the Vite dev server seems to have a major issue with file2 and index.html both referencing main.js. Initially everything works OK but on each subsequent change of the sources files, the server will load in a different version of the main.js file (instancing both) and doesn't scrub the original as you can see below in my Chrome session: This duplication of modules will cause all manner of subtle (or sometimes obvious) bugs in a sufficiently complex webapp. If I move the class definition of A to a different module that isn't referenced directly by index.html (and update the imports accordingly) the problem will go away. I saw some other discussions about circular references acting up with Vite but nothing matched this one very closely so thought it might be useful to discuss here. Not sure if it should be reported as a bug but it was certainly very confusing to figure out what was going wrong and it would be much better for uses if Vite could report an error that it doesn't like this setup if there is no better way to address this. I'm attaching the minimal project, which I tested this on using Vite 6.0.6. vite-test.zip Let me know if I should report this as a bug report. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
It looks like the issue doesn't happen when - <script type="module" src="main.js"></script>
+ <script type="module" src="/main.js"></script> With this, Vite rewrites html properly after <script type="module" src="/vite-test/main.js?t=1735877176556"></script> I think this is a bug as Vite should support script's |
Beta Was this translation helpful? Give feedback.
It looks like the issue doesn't happen when
src="/main.js"
:With this, Vite rewrites html properly after
main.js
changes like below, so there's no duplicate modules after reload.I think this is a bug as Vite should support script's
src
uniformly regardless of relative or absolute path. Please feel to submit an issue.