David’s template provides not just the starter component code but also a nice readme, issue template, and publish-to-NPM flow.
It’s also always interesting to see how different developers structure their web component JavaScript. David’s code includes a neat and interesting approach to registering the comoponent, and favours setup being written in the connectedCallback()
.
Here are a couple of his real web components which started from the template:
- link-peek (really nice and here’s David’s corresponding explainer)
- mastodon-post (explainer)
Incidentally, I noticed the comment querying where event listeners should go and referencing Hawk Ticehurst’s article You're (probably) using connectedCallback wrong. While their seems to be a degree of validity there, I’m not going to sweat it. I’ve checked Keith Cirkel’s advice on this, which is:
If your component has additional set up logic, like adding event listeners, then the
constructor()
isn't the best place for that - as the Web Component isn't yet inserted into (or connected) to a DOM tree, and so it won't have a parent. For that, you'll need a lifecycle callback.
I note that even Hawk Ticehurst isn’t 100% sure about the constructor approach.
So I’m gonna go with putting event listeners in callbacks per Keith and David’s approach.