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

Custom element .js file not being generated #217

Closed chakanish closed 4 years ago

chakanish commented 4 years ago

Hi,

I tried using the vue-custom-element NPM module with my vue cli 4 app.

the main.js looks like this:

_import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import store from "./store"; import i18n from "./i18n"; import vuetify from "./plugins/vuetify"; import SvgTransition from "vue-svg-transition"; import { initFbSdk } from "./lib/FacebookSdk"; import VueCustomElement from "vue-custom-element"; import WidgetView from "./components/Widgets/WidgetView.vue";

Vue.use(VueCustomElement); Vue.customElement("WidgetView", WidgetView);

Vue.use(SvgTransition); Vue.config.productionTip = false;

new Vue({ router, store, i18n, VueCustomElement, vuetify, render: (h) => h(App), }).$mount("#app");_

However when I run the npm run build the corresponding WidgetView.js file is not generated in the dist folder.

I am quite new to this so any help will be appreciated.

karol-f commented 4 years ago

Hi, It will not generate separate WidgetView.js (BTW You should have dash separated name or it won't work - widget-view).

Just load main.js and then use <widget-view> in your HTML.

You can also lazy split it to separate file or use webpack separate entry points.

chakanish commented 4 years ago

@karol-f Thanks for the prompt response.

I want this component to be served over a cdn link so Should i host the main.js in the cdn server?

Appreciate the help again.

karol-f commented 4 years ago

There are few options, Maybe do it like that:

let widgets = [
    { name: 'widget-view1', props: ['prop1'], file: './components/WidgetView1.vue' },
    { name: 'widget-view1', props: ['prop1'], file: './components/WidgetView2.vue' },
];
Vue.config.ignoredElements = widgets.map((name) => `${name}`));

widgets.forEach((widget) => {
    Vue.customElement("test-component", () => import(`./components/${widget.file}`));
}))

If I don't miss something it should load component only when used in HTML. Downside is that if main.js file is loaded from CDN in different domain, You have to tell Webpack from what address grab JS chunks with widgets - use __webpack_public_path__ (https://webpack.js.org/guides/public-path/#on-the-fly)

e.g.

export function setPath (path) {
    __webpack_public_path__ =  path;
}

and run it on beginning, before widgets.forEach((widget) => ...

On the other hand You can just load all widgets at once in main.js:

 Vue.customElement("test-component", WidgetView1);

Regards!