skip to Main Content

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


  1. 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 one src 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:

    import app from '.../my-app';
    app.mount(...);
    

    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 = ... and app.mount(...).

    In this case it could be:

    export default function myAppPlugin(app, options) {
      app.use(router);
      ...
    }
    

    In any other entry point that needs to reuse this logic:

    import { createApp } from 'vue'
    import App from './App.vue'
    import myAppPlugin from '.../my-app-plugin';
    const app = createApp(App)
    app.use(myAppPlugin);
    app.mount('#app');
    
    Login or Signup to reply.
  2. I think you can approach it in a different way,
    for example:
    app.js

    import { createApp } from 'vue'
    import router from './router'
    import App from './App.vue'
    import { initApp, testFn } from "./index.js" // This is your index file
    const app = createApp(App)
    app.use(router)
    app.mount('#app')
    
    initApp(app);
    testFn();
    
    

    index.js

    let app;
    export function initApp(_app) {
      app = _app
    }
    
    // So you can also use the app in this file
    export function testFn() {
      console.log(app)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search