-
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
HMR error: Cannot access '...' before initialization #3033
Comments
@ygj6 Hello. Why do you think that it is react problem? I think react only calls render fn. We can't access variable from module, that already depend on us. But this app works - because we access variable not instantly(during module loading), but during render. import { STATES_CONST } from './states';
console.log(STATES_CONST); // this line break all because we try access STATES_CONST during module loading
class Component extends PureComponent {
render() {
return <div>States const: {STATES_CONST}</div>;
}
} maybe this issue has to be fixed like this(this is Vite code)? try {
const newMod = await import(
/* @vite-ignore */
base +
path.slice(1) +
`?import&t=${timestamp}${query ? `&${query}` : ''}`);
moduleMap.set(dep, newMod);
}
catch (e) {
warnFailedFetch(e, dep);
location.reload(); // I was added this line
} P.S. this hmr fails because during loading of dependencies of Component.tsx after hmr there is situation that ComponentOther.tsx loads before router.ts. And router.ts access variable during module loading(this is forbidden) maybe it's project problem, but I think Vite should reload the page in this case? |
I think there is a bug in plugin-react-refresh, but we can not reload on error. Check out the warning message "This could be due to syntax errors or importing non-existent modules.". When the user is typing and there is an error, we want to wait until a successful run to update the page with HMR, or the state will be lost after the full reload while the user is typing (for example if it is using auto save) |
@patak-js how about this idea? We can't update this module because of imports loop, but we can prevent our page to be broken. Now every module call current code here: plugin-react-refresh/index.js const runtimeCode = `
const exports = {}
${fs.readFileSync(runtimeFilePath, 'utf-8')}
let queue = false;
exports.queueReactRefresh = () => (queue = true); // do not debounce. Only set flag
window.flushReactRefresh = () => { // set window fn to flush updates. We call them *after* successful import
if (queue) {
exports.performReactRefresh();
queue = false;
}
}
export default exports
...
const footer = `
if (import.meta.hot) {
window.$RefreshReg$ = prevRefreshReg;
window.$RefreshSig$ = prevRefreshSig;
${
isReasonReact || isRefreshBoundary(result.ast)
? `import.meta.hot.accept();`
: ``
}
RefreshRuntime.queueReactRefresh(); // call here queue instead of debounce performReactRefresh
}` current code here: vite/dist/client/client.js try {
const newMod = await import(
/* @vite-ignore */
base +
path.slice(1) +
`?import&t=${timestamp}${query ? `&${query}` : ''}`);
window.flushReactRefresh?.(); // flush updates after successful import
moduleMap.set(dep, newMod);
}
catch (e) {
warnFailedFetch(e, dep);
} There is another option how to fix this by one line. We can make something like this: try {
const newMod = await import(
/* @vite-ignore */
base +
path.slice(1) +
`?import&t=${timestamp}${query ? `&${query}` : ''}`);
moduleMap.set(dep, newMod);
}
catch (e) {
clearTimeout(window.__vite_plugin_react_timeout); // I added this line
warnFailedFetch(e, dep);
} |
I understood that we can't write code connected to react inside Vite client... Needs more complex solution |
This comment was marked as spam.
This comment was marked as spam.
I have the same question when i use store and axios in route beforeEach |
This comment was marked as duplicate.
This comment was marked as duplicate.
This comment was marked as spam.
This comment was marked as spam.
3 similar comments
This comment was marked as spam.
This comment was marked as spam.
This comment was marked as spam.
This comment was marked as spam.
This comment was marked as spam.
This comment was marked as spam.
@xSorc were you able to identify the source of this issue? I'm sure there are thousands of Vite apps with react and connected components, so there must be something specific that is causing this issue. I've had to turn off HMR for the app to load properly. |
@tzusman I can't understand the whole picture. All I know that the problem is caused by imports loop. That works during first load. But when I tried to change function connect(Cmp: ComponentType) {
return Cmp
}
class Component extends PureComponent {
render() {
return <div>States const: {STATES_CONST}</div>;
}
}
export default connect(Component); to lines function connect(Cmp: ComponentType) {
return Cmp
}
class Component extends PureComponent {
render() {
return <div>States const: {STATES_CONST}</div>;
}
}
const a = connect(Component);
export default a; the problem is gone. I have no idea how this works The structure may be simplified to this My advice is to remove a dependency loop. I've done it in my project. This is the easiest way to handle it right now |
This comment was marked as spam.
This comment was marked as spam.
This comment was marked as spam.
This comment was marked as spam.
Stumbled onto some tips from parceljs that may help with this issue:
I actually was getting a hard refresh way more than I was expecting before following each of those tips, now I'm seeing fast refresh everywhere and haven't seen that error yet. |
This comment was marked as spam.
This comment was marked as spam.
@matt-erhart I had the same issue but your last tip really helped me resolve the issue, thank you so much! What I had:
Changed it to:
So I just moved |
For future travelers: If you see the |
vs code extension to help find circular dependencies https://marketplace.visualstudio.com/items?itemName=iulian-radu-at.find-unused-exports source https://twitter.com/alecdotbiz/status/1461729042604998664?t=MJApPe1FxTzI6zMMXXSktQ&s=19 |
This comment was marked as spam.
This comment was marked as spam.
This comment was marked as spam.
This comment was marked as spam.
1 similar comment
This comment was marked as spam.
This comment was marked as spam.
I found this solution which prevents HMR from breaking if there are circular dependencies, but I'm not sure what are the drawbacks // vite.config.ts
export default defineConfig({
plugins: [
// your plugins,
{
name: "singleHMR",
handleHotUpdate({ modules }) {
modules.map((m) => {
m.importedModules = new Set();
m.importers = new Set();
});
return modules;
},
},
],
}); |
woow! In my project I was having problems using |
You saved my day. We have a huge vue3 project and were stuck with vite 2. vite 3 and vite 4 both had the HMR issue described here, but this fix works perfectly. Thanks again. |
same. vite@4.0.4 |
same |
I had the same. My issue was this case |
STOP commenting “same” and upvote first comment please. Avoid this all over GitHub, your are sending useless notifications to everyone who had subscribed to the issue. Thanks. |
{
name: "singleHMR",
handleHotUpdate({ modules }) {
modules.map((m) => {
m.importedModules = new Set();
m.importers = new Set();
});
return modules;
},
}
加了这段代码确实热更新不再报错了,但是每次更改样式的时候不会刷新。我看了下文档,你这个方法在vite3x才支持,vite2x目前还没有,我觉得可能是我的vite版本低的问题
vue:3.2.25
vite:2.8.0 |
多谢大佬,检查了下代码,发现了问题! |
@SuspiciousLookingOwl did you ever find any negatives to doing that? I'm also seeing that this is fixing it for me, but unsure if it also breaks anything |
Anyone have any success finding the circular dependencies when madge doesn't think there are any? |
same, vite@4.1.1 |
Thanks @michaeljohansen!
Here's how I did it:
This pointed me to entries like:
I fixed it by moving |
same, vite@4.1.4 |
In my case, I had a hidden circular dependency cycle (madge couldn't find it) with react-router and use-react-router-breadcrumbs. I had implemented a custom breadcrumbing system with those two and CRA at the time. I fixed it by upgrading to a newer version of This is probably a specific case, but hopefully my findings can be useful to someone in a similar situation! |
Vite is more strict the `import`s it accepts. These imports are fixed. Additionally, the Redux store is now exported form a separate file (other than `index.tsx`. This was done to workaround vitejs/vite#3033. The circular imports and Redux store don't play nice, so the circular import was removed.
Is there any progress regarding this issue at present? |
I have a different perspective on the error you mentioned. While it might not be directly related to the issue you encountered, consider it as a subtle suggestion. For instance, the code snippet below would trigger a reference error due to the "temporary dead zone". When the bar()
const foo = 'foo'
function bar() {
console.log(foo)
} Therefore, to fix this problem, you could try using the |
Thanks, this pointed me to my own problem - I had a file that exported a few constants AND 1 additional React component. In other words - I had a mix of React and non-React exports from the same file. As soon as I removed the export for the React component (leaving just regular non-React exports) - the error disappeared. |
it's useful, thank you very much |
Solved the issue about 'Cannot access ...' |
Describe the bug
The error happens when I try to edit component, that
connect
function (redux)Seems weird, but it's not so rare case when project uses routers like UiRouter or Universal router
I expect that component will be updated with HMR without errors or may be reload the page but not to throw an error
Reproduction
Repo: https://github.com/xSorc/test-vite-fast-refresh-loop-dependency
To reproduce this error you need to open the project and try to edit
Component.tsx
. You will see an errorSystem Info
Output of
npx envinfo --system --npmPackages vite,@vitejs/plugin-vue --binaries --browsers
:Used package manager:
Logs
Before submitting the issue, please make sure you do the following
The text was updated successfully, but these errors were encountered: