Build Your Own JavaScript Micro-Library Using Web Components: Part 4 of 4
In this capstone tutorial, we're going to actually use the micro-library in app code so you can see how the micro-library makes things easier for developers in real world development. In the previous steps of this 4-part tutorial, this is what we accomplished: In this final tutorial, we will now refactor an example component to use the @Component decorator and the attachShadow function from our micro-library. We're refactoring a file, packages/component/src/card/Card.ts , which contains the CardComponent class. This is a regular Web Components custom element. To get it to use our micro-library, we first import Component and attachShadow from our micro-library. Next, we add the Component decorator to CardComponent . We remove the line at the bottom of the file that registers the component, noting the tag name in-card . Remove customElements.define('in-card', CardComponent); . The above code is now automated by our micro-library. We set the selector property to the ElementMeta passed into Component to in-card , the same string originally used to register the component. Next, we move the content of the style tag in the constructor to the new style property on ElementMeta . We do the same for the template of CardComponent . We migrate the HTML to the new template property until the ElementMeta is filled in. Next, we remove everything in the constructor and replace it with a call to our micro-library's attachShadow function, passing in this to the first argument. This automates Shadow DOM setup. To make sure everything is working properly, this is where we start up the development server and observe the changes in the browser. Nothing should have changed about the user interface. Everything should appear the same. Our CardComponent has now been successfully refactored to use the micro-library's utilities, eliminating boilerplate and making the actual component code easier to reason about. That completes this 4-part tutorial series on building a micro-library for developing with Web Components. Our micro-library supports autonomous and form-associated custom elements. It enables developers to automate custom element setup as well as Shadow DOM setup, so they can focus on the unique functionality of their components. In the long run, these efficiencies add up to a lot of saved time and cognitive effort. If you want to dive more into ways to build long-lived web apps that use Web Components and avoid lock-in into specific JavaScript frameworks, check out Fullstack Web Components: Complete Guide to Building UI Libraries with Web Components.