I finally started playing around with WebC, and I think a relatively small feature —
webc:import — will make it an especially compelling choice for building components that can be easily shared between Eleventy projects.
What is WebC?
I've only scratched the surface of what WebC can do, but I already see there's a lot to like:
- Optionally scoped CSS, adding a prefix class to help prevent selector collisions across styles
- Asynchronous support across the board!
These tentpole features sound like a first-rate foundation for building reusable components, but one small note in the docs has me just as excited:
New in WebC v0.6.2, you can import directly from an installed
Sharing components between projects
Imagine you have multiple Eleventy projects that share a common need; namely, "not enough confetti."
You've been using Nunjucks macros to build a pre-rendered component that brings the ‘fetti every site so desperately needs, but there's a nagging problem: macros can't be shared, meaning every fix or feature has to be manually ported to each project.
(This feels especially frustrating because NPM is sitting right there, managing all the other packaged dependencies for each of your projects.)
webc:import attribute is, I think, the answer.
An overwrought demo
I'm the kind of learner who benefits from a good practical exercise, so I decided to hoist
webc:import out of the docs and into some code to see how it all works.
First, I put together a project to simulate a source repo that might contain our shared components. Next, I created an Eleventy project as a stand-in for a site that needs some confetti, and installed the shared components package as a dependency:
npm install ashur/demo-shared-webc-components#semver:^v0.1.0
Finally, I dropped the component onto my site's home page template:
<confetti-button text="Get Ready for Confetti" webc:import="npm:@aaashur/demo-shared-webc-components" ></confetti-button>
(I also added some site-specific styles to the button itself, as you might do in a real project.)
That's it! A few quick steps and voilà!
Adding a confetti-blasting button to our site is now a simple, straightforward process. What's more, any future updates to
<confetti-button> are easily adopted across multiple sites just by updating the NPM package.
A nice surprise
<script type="module"> import confetti from 'https://cdn.skypack.dev/canvas-confetti';
and much to my delight, it just worked. Yay, web standards! 🎉