Search code examples
javascriptvue.jsvuejs3vue-clivue-composition-api

Vue 3 with Composition API different object structure for getting context/globalProperties with Vue-CLI 4 in dev build or production build?


Why is the object structure from the getCurrentInstance() result with the Composition API different in development or production build?


I use the following pattern for adding globals to my Vue instance:

    export default {
      install(app) {
        const _projectFile = new ProjectFile(app);
    
        //* This will help for accessing the store in other files (plugins)
        app.config.globalProperties.$projectProperties = _projectFile;
    
        //* This will expose the store in components with this.$store
        app.provide('$projectProperties', _projectFile);
      }
    };

I am initiating this in my main.js, with a bunch of other stuff (this all works fine).

    import App from './App.vue'; // Main Vue component
    const app = createApp(App)
    .use(projectProperties);
    app.mount('#app');

The actual weirdness starts here.. When trying to access my globalProperties from the setup() (Compostion API) in ./App.vue. I get a different object structure for getCurrentInstance() when running:

  1. vue-cli-service serve (development)
  2. vue-cli-service build (production)

./App.vue

  setup() {
    const _instance = getCurrentInstance();

    onMounted(async function() {
      // This one is only valid from vue-cli-service serve
      const { $store, $router, $projectProperties } = _instance.ctx;

      // This will work for both vue-cli-service serve & build
      const { $store, $router, $projectProperties } = _instance.appContext.app.config.globalProperties;

      // Other non relevant code down here

    });
  },

So this will not work in my production build: const { $store, $router, $projectProperties } = _instance.ctx;

I don't get why the getCurrentInstance().ctx points towards the globalProperties object with cli-service serve but does not contain the globalProperties in the cli-service build?


Solution

  • It turns out ctx is intended for development mode only. ctx exposes the global properties for easier console inspection.

    If you need the global properties in both development and production modes, you need to stick with _instance.appContext.app.config.globalProperties.