I've been tackling a project in Svelte, but it involves some web components.
The current hurdle I'm facing is with web components defined using the customElements.define()
function in Typescript, as they are not accessible unless specifically imported in the user component.
For instance, consider a web component defined like this:
// File name: oneWebComponent.js
export class OneWebComponent extends HTMLElement {
...
customElements.define('one-web-component', OneWebComponent);
}
Then, there's another JS file with a "factory" function that generates various types of Web Components:
export const createElement = (tagName) => {
return document.createElement(tagName);
}
When calling it as
createElement('one-web-component')
, the resulting component isn't the one specified in OneWebComponent
. This can be identified by the undefined functions (error: XXX is not a function).
However, if I import oneWebComponent.js
in the factory file as shown below, it functions correctly:
// Newly added line:
import './oneWebComponent.js';
export const createElement = (tagName) => {
return document.createElement(tagName);
}
This implies that for multiple web component types and repeated calls to the factory function, I'd need to import each type in every instance, which is cumbersome.
Is there a way to make the components defined by customElements.define()
globally accessible without individual imports?
In other words, no imports necessary, simply pass the tag name into document.createElement()
for correct web component creation.
Could it be a configuration oversight on my part?
Appreciate any assistance in this matter!