Importing external components in WebC via NPM

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?

WebC is a new tool that adds first-class component support to Eleventy without all the client-side JavaScript that commonly bloats sites built with similar tools. (Even cooler, it's framework-agnostic!)

I've only scratched the surface of what WebC can do, but I already see there's a lot to like:

  • Support for Vue-like single-file component definitions — component HTML, CSS, and JavaScript all in one file
  • 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 npm package.

Go on...

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's small-but-mighty 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:

    text="Get Ready for Confetti"

(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

I'm not in the confetti-drawing game, so I reached for ol' canvas-confetti. On a hunch, I imported a CDN-hosted copy of the package to my <confetti-button> example component:

<script type="module">
    import confetti from '';

and much to my delight, it just worked. Yay, web standards! 🎉