In my vue3 app my entry is: main.js
import { createApp } from 'vue'
import router from './router'
import App from './App.vue'
const app = createApp(App)
app.use(router)
app.mount('#app')
//if I do console.log(app) I have my app correctly initialized
export default app
in a separate file index.js
import app from '../renderer/src/main.js'
console.log(app)
//...rest of code I need to use app.component()
I have this error: ReferenceError: Cannot access ‘app’ before initialization.
I checked the paths, and they are correct. As I mentioned in the code of main.js, my app is correctly initialized since I can see it with a console.log, but I can’t export it correctly. What I want is to be able to use app.component and app.use in a separate file.
2
Answers
That there’s a problem with importing
app
could mean that there’s unresolved circular dependency or a problem with the project that is caused by multiple source roots. In a basic scenario there’s only onesrc
at project root, anything else requires additional configuration.This is design problem that isn’t exclusive to Vue.
That application instance needs to be reused without calling
mount
and don’t cause circular dependencies could mean that it needs to be extracted to separate module, which could be imported in entry points:The code from
my-app
could be extracted to a function for reusability.But in Vue a reusable piece of an application is a plugin. It’s basically a function that receives application instance and can do anything that is needed with it, including installing other plugins and registering global components, i.e. it can do anything that is usually done between
const app = ...
andapp.mount(...)
.In this case it could be:
In any other entry point that needs to reuse this logic:
I think you can approach it in a different way,
for example:
app.js
index.js