karol-f / vue-custom-element

Vue Custom Element - Web Components' Custom Elements for Vue.js
https://karol-f.github.io/vue-custom-element/
MIT License
1.97k stars 187 forks source link

Using Vue.customElement() in combination with Vue.use() plugin #183

Closed sebsobseb closed 4 years ago

sebsobseb commented 4 years ago

Hi,

In our company we use a custom made Vue plugin which provides of set of global Vue components we can use throughout our applications:

(app.js) import CompanyVueTemplates from 'company-vue-templates'; Vue.use(CompanyVueTemplates);

We can then use components in our HTML for example: <component-a></component-a>.

In a specific application we want to use Vue-custom-element (in combination with our plugin). So, my question is: How can i pass ComponentA to the customElement function?

Vue.customElement('custom-component-a', ComponentA);

Gives me an error: Uncaught ReferenceError: ComponentA is not defined

Thanks!

karol-f commented 4 years ago

Maybe just write dummy Vue Custom Element with template like

<template><component-a></component-a></template>

But You won't have proper props exposed. My suggestion is to just import these components individually and make Vue Custom Elements from them.

sebsobseb commented 4 years ago

@karol-f thanks for the suggestions, thats what's working indeed:

import ComponentA from 'company-vue-templates/path/to/components/ComponentA'; Vue.customElement('custom-component-a', ComponentA);

But, isn't there another way of importing these components without having to specify a path manually for each component?

karol-f commented 4 years ago

You can use webpack's feature called require.context, assuming that your components has proper name:

function requireAll(requireContext) {
    return requireContext.keys().forEach((module) => {
        const importedModule = requireContext(module).default;
        Vue.customElement(importedModule.name, importedModule);
    });
}

// 'true' means that it search in sub-directories
requireAll(require.context('./company-vue-templates/path/to/components/', true, /\.vue$/));