cornflourblue / vue-3-pinia-registration-login-example

Vue 3 + Pinia - User Registration and Login Example & Tutorial
https://jasonwatmore.com/post/2022/07/25/vue-3-pinia-user-registration-and-login-example-tutorial
146 stars 71 forks source link

Importing router in store causes circular dependency which breaks HMR in newest version of Vite #2

Open astamant-nosm opened 1 year ago

astamant-nosm commented 1 year ago

Disclaimer: I'm new to Vite and Vue and could be wrong about this.

After upgrading Vite to the latest version, I started getting the following HMR reload error:

client.ts:113 ReferenceError: Cannot access 'ComponentName' before initialization
client.ts:115 [hmr] Failed to reload component. This could be due to syntax errors or importing non-existent modules. (see errors above)

As soon as I remove the router import statement in auth.store.js, this error no longer happens and I can use HMR like I used to.

Is there a way to access the router without re-importing it? I think that would solve my issue.

Here are my dependencies:

    "dependencies": {
        ...
        "@vitejs/plugin-vue": "^3.2.0",
        "pinia": "^2.0.13",
        "vite": "^3.2.5",
        "vue": "^3.2.33",
        "vue-router": "^4.0.14",
        "vue3-datepicker": "^0.3.4"
    },
    "devDependencies": {
        "eslint": "^8.29.0",
        "eslint-plugin-vue": "^9.8.0",
        "vite-plugin-eslint": "^1.8.1",
        "vite-plugin-mkcert": "^1.10.1"
    }
astamant-nosm commented 1 year ago

Actually, I think I may have solved it.

// main.js
import { createApp, markRaw  } from 'vue';
import { createPinia } from 'pinia';
import { router } from './router';
import App from './App.vue';

const app = createApp(App);
const pinia = createPinia();
pinia.use(({ store }) => {
    store.$router = markRaw(router);
});
app.use(pinia);
app.use(router);

app.mount('#app');

And then in stores:

this.$router.push(this.returnUrl) // or w/e you need to do