Web Components — Webpack bundled
Html, CSS and JS in separate files ( almost ) , with Webpack bundling
Let’s create a Header WebComponent. Built of two parts ( header.html, and header.js )
It uses ideas from — https://css-tricks.com/styling-a-web-component/ , i.e. CSS custom properties penetrate the Shadow DOM!
The style and the html are in a header.html file.
Added along is the main styles.css
Let’s look at the header.js file
Pretty standard WebComponent — has a constructor, and within it’s connectedCallback , calls render.
The magic is in the htmlToElement — which takes the html and creates two elements out of it, from the template.
- CssContent element
- HtmlContent element
and finally the render appends both the elements to the shadowRoot.
Within index.js, register the custom element
import AppHeader from '../components/appHeader/header';
import styles from '../src/styles.css';customElements.define('app-header', AppHeader);
And finally the webpack.config.js , which binds everything together
The html-loader takes care of making the html file available within the .js file.