HB's Thoughts

I try to think really hard.

11/26/2024

Vue Router & Main file

When starting a new Vue project, I use the Quick Start section of the Vue website. Then, I make a few small changes before adding the project to the Source Control bank.

From the questions that npm create vue@latest asks me, I almost always choose:

 Add TypeScript? ... no / YES
 Add Vue Router for Single Page Application development? ... no / YES
 Add Pinia for state management? ... no / YES
 Add an End-to-End Testing Solution? » Playwright

The others, if necessary during development.

After executing all the instructions that appear on the screen, you get a project ready to start. The first thing I edit is the Main file - src/main.ts.

At the beginning, it looks like this:

import './assets/main.css'

import { createApp } from 'vue'
import { createPinia } from 'pinia'

import App from './App.vue'
import router from './router'

const app = createApp(App)

app.use(createPinia())
app.use(router)

app.mount('#app')

There is a small hidden secret here that you probably don't know. Sometimes, it may happen that the Vue application loads before the router is initialized. To avoid the appearance of such Vue jokes, I edit src/main.ts:

import "./assets/main.css";

import { createApp } from "vue";
import { createPinia } from "pinia";

import App from "./App.vue";

initializeApp();

async function initializeApp(): Promise<void> {
  const app = createApp(App);
  const pinia = createPinia();

  const { default: router } = await import("@/router");

  app.use(router);
  app.use(pinia);

  await router.isReady();
  app.mount("#app");
}

This way, the router is initialized before the Vue application is loaded. A tiny trick that will save you from possible future problems.


If you have an opinion or questions about the article, don't hesitate to share them.

Join the open discussion on GitHub.


Competence: Pro