Skip to content
Rafał Lorenz edited this page May 26, 2017 · 8 revisions

web-component is a lightweight library providing interface for building web components.

Package provides a decorator function that allows you to:

  • easy define Custom Elements
  • styling a custom element
  • creating elements from a template
  • attribute binding
  • encapsulate style and markup using Shadow DOM
  • extending other custom elements or even the browser's built-in HTML
import { WebComponent } from 'web-component'

@WebComponent('hello-world', {
  template: require('./hello-world.html'),// provide template
  styles: require('./hello-world.css'), //provide styles
  extends: 'button', //default does not extends any
  shadowDOM: true //default false
})
export class HelloWorld extends HTMLElement {}

If shadowDOM option is set to true then template and styles will be attached to shadowRoot. If there is no shadowRoot, it will be created with mode open.

Important

@WebComponent decorator return a constructor returned by document.registerElement, which you then can use to call:

@WebComponent('hello-world')
class FooElement extends HTMLElement {
  ...
}
const FooInstance = new FooElement();
document.querySelector('body').appendChild(FooInstance);

Using the constructor of FooElement directly without WebComponent decorator, will throw an InvalidConstructor - exception.

class FooElement extends HTMLElement {
  ...
}
const FooElementCtor = document.registerElement('element-name',FooElement);
const FooInstance = new FooElement();     //will throw InvalidConstructor
const FooInstance = new FooElementCtor(); //will work
document.querySelector('body').appendChild(FooInstance);

Calling the constructor directly may be supported in future, or it is just an error in the spec.

Clone this wiki locally