Search code examples
javascriptvue.jsvuejs2rollup

Programmatically created Vue component missing global properties defined on Vue.prototype


I have an issue when creating an instance of a vue component imported from a bundled rollup library, I add a global property to the root Vue instance using Vue.prototype and it is shared across all of my components, However when i create a new instance using the Vue.extend method, the newly created component has none of the prototype properties or globals they all simply return undefined.



//Main.js
Vue.prototype.$example = 'Hello there!';

//////////////////////////////

new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')


//App.vue
import { MyDynamicComponent } from 'my-bundled-rollup-library';
export default {
    created() {

        var DynamicComponent = Vue.extend(MyDynamicComponent);

        console.log(this.$example) //Returns 'Hello there!' (correct)
        var instance = new DynamicComponent({
            propsData: {
                hello:'world',
            },
        })

        ///////////////////////////////////////////

        console.log(instance.$example) //Returns undefined (does not have the property)
    }
}

And here is an example of the component before it's bundled

//MyDynamicComponent.vue
const MyDynamicComponent = {
     props:{
          hello:{
               type:String
          }
     },
     created() {
          console.log(this.$example) //undefined
     }
}

export default component
export { MyDynamicComponent as MyDynamicComponent }

My first thought is that somehow the component is using a different Vue instance than the one of Vue.extend


Solution

  • After rm -rf node_modules and reinstalling and trying to recompile my library with rollup again, roll up threw an error that it was not throwing before over an alias to use the Vue runtime+compiler package.

    [!] Error: Cannot find module 'vue/dist/vue.esm.js'
    

    My rollup.config file had

    
    import vue from 'rollup-plugin-vue';
    
    import alias from '@rollup/plugin-alias';
    
    export default {
        plugins: {
            alias({
                entries: [
                    //Removing this line fixed the problem
                    //{ find: 'vue', replacement: require.resolve('vue/dist/vue.esm.js') },
                ],
            }),
            vue,
        }
    }
    

    So the lesson learned is, when things are being strange, rm -rf node_modules and rebuild everything again.