How can I use LitElement with Webpacker (rails Webpack) for custom Web Components?

955 views Asked by At

For those who may not know Rails now uses Webpacker, an integration with Webpack. There is a /packs dir that will get transpiled for use on a html page:

<script src="/packs/bundle-06cd8a4ad388853ace59.js"></script>

I have written a test web component.

import { LitElement, html } from 'lit-element';


class TestComponent extends LitElement {

  render(){
    return html`
      <!-- template content -->
      <p>ZZZZZZZZZZ</p>
    `;
  }
}
customElements.define('test-component', TestComponent);

I'm importing this into my packs/bundle.js as:

import '../web_components/test-component'

In the browser I get the error:

Uncaught TypeError: Class constructor LitElement cannot be invoked without 'new'

Webpack is turning this into:

var TestComponent = function (_LitElement) {
  _inherits(TestComponent, _LitElement);

  function TestComponent() {
    _classCallCheck(this, TestComponent);

    return _possibleConstructorReturn(this, (TestComponent.__proto__ || Object.getPrototypeOf(TestComponent)).apply(this, arguments));
  }

  _createClass(TestComponent, [{
    key: 'render',
    value: function render() {
      return Object(__WEBPACK_IMPORTED_MODULE_0_lit_element__["b" /* html */])(_templateObject);
    }
  }]);

  return TestComponent;
}(__WEBPACK_IMPORTED_MODULE_0_lit_element__["a" /* LitElement */]);

customElements.define('test-component', TestComponent);

I'm not really sure of how to make this work, but I would really love to get started using web components.

Please help!!

1

There are 1 answers

0
dcts On

This seems to be a common issue.

Found a solution that works for me, hopefully thats helpfull to you too. Just add the following script tag inside application.html.erb. It's a polyfill, you can read more about it here

<!-- ADD POLYFILL  -->
<script type="text/javascript" src="https://unpkg.com/@webcomponents/[email protected]/custom-elements-es5-adapter.js"></script>

<!-- be sure that the webpack tags are AFTER the polyfill -->
<%= javascript_include_tag 'application' %>
<%= javascript_pack_tag 'application' %>
<%= yield %>

the polyfill can also be added through NPM, but I prefere to just use the CDN