Search code examples
web-componentcustom-element

Publishing Custom Elements, naming conventions, best practices?


I am about to make my Custom Element <card-t> public

pre-release is at: https://github.com/card-ts/playingcardts

Suggestions and enhancements much appreciated!

Couple of questions:

Naming Custom Elements

There is: https://www.webcomponents.org/community/articles/how-should-i-name-my-element
but it doesn't get past "must include a hyphen"

I went with element.card-t.js for sorting purposes.

Other best practices ??

Wrapping in IIFE & ES Modules?

The Custom Elements gets created in the Global Namespace, and doesn't return anything like a library does.

Wrapping in an IIFE should be enough?

Is there value in loading it as module?

<script type="module" src="element.card-t.js">

Extending Custom Elements

Should we by default return the class definition so extending is easier?


Solution

  • Since this is an opinion question these are my opinions:

    Naming Custom Elements

    I always name my JS file based on my class name and my class name is just the tag name but capitalized. So my tag <my-thing> would have a class name of MyThing and my filename would be components/MyThing.js

    Wrapping in IIFE & ES Modules?

    I create all of my code in ES6+ and then I create an additional ES5 CommonJS version and an ES5 IIFE version and let people load what they want.

    I use rollup and my component-build-tools to create my various versions. component-build-tools component-build-tools also combines all dependencies of a component into the output file. This can lead to some replication, but most of the time that is small enough I don't mind.

    My components end up with their templates and locale strings embedded into the published files. This is a feature of component-build-tools.

    Extending Custom Elements

    As a general rule I expose the class name in all three formats of my files. This does help with extending my components, yet I doubt that many people will ever want to do that.

    Where to place the files.

    The hardest thing is where to place the files so they are easily accessed by the web page.

    I have a build step that copies my files from the node_modules folder into a dist folder. This was the easiest thing for me to know exactly where my files are located.

    Doing this allows me to npm install anything and then still get their files into a location I know and can use. But it also has lead to me not worrying greatly about where my files end up in my repo.

    I do tend to have a dist folder and in there I have:

    dist
     +- js
         +- components
             +- MyThing.js
             +- MyThing.min.js
             +- AnotherThing.js
             +- AnotherThing.min.js
             +- SoOn.js
             +- SoOn.min.js