Issue
I am working on a Svelte project, but it contains some web components.
The issue I am facing is that some web components defined by the customElements.define()
Typescript function are not usable unless I import them specifically in the user component.
For example, a web component is defined in the following way:
// File name is oneWebComponent.js
export class OneWebComponent extends HTMLElement {
...
customElements.define('one-web-component', OneWebComponent);
}
Then, there is another JS file, which contains a "factory" function that creates different types of Web Components:
export const createElement = (tagName) => {
return document.createElement(tagName);
}
If I call it like createElement('one-web-component')
, the resulting component is not really the one defined in OneWebComponent
. I know that because the functions defined there are not callable (error: XXX is not a function).
But if I import oneWebComponent.js
in the factory file like below, it works correctly:
// This line is newly added:
import './oneWebComponent.js';
export const createElement = (tagName) => {
return document.createElement(tagName);
}
That means, if I have multiple types of web components, and the factory function is called in multiple places, I will have to import each type of web component in each place, which is tedious.
I wonder if there is a way to just make the components defined by customElements.define()
globally usable?
That means, no imports needed, just passing the tag name into document.createElement()
and it will create the web component correctly.
Am I missing any configs?
Thanks in advance!
Solution
As @Bergi pointed out, the customElements.define()
function is not executed if the file is not imported anywhere.
So I only needed to import all of the web components in the top level of the app, a file like app.svelte
or main.js
for example, then the function will run, and the tags are defined and usable across the app.
Answered By - powerseed
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.