custom-element-styles

1.0.1 • Public • Published

custom-element-styles

Automatically inject styles into a custom element's Shadow DOM once it's created.

Similar to insert-css, except for custom elements.

Usage

NPM

styles(Element, css)

Applies the css styles when a ShadowRoot is created on the Element custom element.

require('webcomponents.js')
 
const styles = require('custom-element-styles')
 
const CustomElement = {
  prototype: Object.create(HTMLElement.prototype)
}
 
styles(CustomElement, `
  h1 {
    color: red;
    text-transform: uppercase;
  }
`)
 
CustomElement.prototype.createdCallback = function() {
  var h1 = document.createElement('h1')
  h1.innerText = 'hello world'
  this.createShadowRoot().appendChild(h1)
}
 
// Note: it's important that you assign the styles
// *before* the element is registered.
document.registerElement('custom-element', CustomElement)

Alternatively, using brfs and custom-element:

require('webcomponents.js')
 
const styles        = require('custom-element-styles')
const customElement = require('custom-element')
const fs            = require('fs')
 
const css = fs.readFileSync(require.resolve('./index.css'), 'utf8')
 
const CustomElement = customElement()
  .once('created', function() {
    var h1 = document.createElement('h1')
    h1.innerText = 'hello world'
    this.createShadowRoot().appendChild(h1)
  })
 
styles(CustomElement, css)
 
document.registerElement('custom-element', CustomElement)

See Also

License

MIT. See LICENSE.md for details.

Package Sidebar

Install

npm i custom-element-styles

Weekly Downloads

2

Version

1.0.1

License

MIT

Last publish

Collaborators

  • hughsk