When working with native web components, it is necessary to be able to add class definitions after the page has loaded, especially when new types of components are dynamically added to the DOM.
EDIT: Here's a brief explanation:
In order to define web components, you use a class like this:
customElements.define('my-new-tag', myNewtagClass);
;
Therefore, if you want to introduce a new type of component into the DOM, its corresponding class must be defined. It seems that you cannot programmatically define a global class, as it needs to be defined within the root document/scope.
As of now, the only Pure JavaScript solution I could find is to create the class as a string and insert it using a script in the head of the document.
However, this means having to write the class in this format:
let myClassString = `
class myClass {
....
}`;
const sc = document.createElement('script');
sc.setAttribute('type', 'text/javascript');
sc.innerHTML = myClassString;
window.document.head.appendChild(sc);
Unfortunately, this method isn't very practical in most IDEs...
Is there a way to automate this process during the build (considering I use TypeScript and webpack)?
For instance, can I extract the class from a file where it's normally defined and utilize it as a variable elsewhere?