6

Having set up a web project to use TypeScript/WebPack I cannot get Google Chrome to run the result:

enter image description here

The error reads: "Uncaught TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function."

I learned that a shim is required for transpiling to ES5, but I still can't get this to work. That's probably because I don't want to add a <script> element to the HTML but instead I want to import "../node_modules/@webcomponents/webcomponentsjs/webcomponents-bundle"; in my .ts files.

How can I get this to work without adding <script> elements to my HTML files?

I took my tsconfig.json and webpack.config.js files from this tutorial.

AxD
  • 2,714
  • 3
  • 31
  • 53

1 Answers1

6

Here's the solution:

npm install @webcomponents/webcomponentsjs --save-dev
import "@webcomponents/webcomponentsjs/webcomponents-bundle";
import '@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js';

...

As far as I can see, this runs smoothly on Chrome, Firefox, Edge and IE11.

AxD
  • 2,714
  • 3
  • 31
  • 53
  • As a rule of thumb, don't include polyfills with your components. Instead, they should be provided by the application consuming the component. I'm not sure if I understood your setup correctly, but _usually_ both `webcomponents-...` and `es5-adapter` are imported using a ` – craPkit Feb 18 '19 at 13:58
  • To give an example for that kind of setup: in my webpack config, there's an `entry` defined for each polyfill, like `{ entry: { polyfills: '@babel/polyfill', 'wc/webcomponents-loader': resolve(__dirname, '../../../node_modules/@webcomponents/webcomponentsjs/webcomponents-loader'), app: resolve(...) }, ... }` – craPkit Feb 18 '19 at 14:00
  • Web components are supposed to be served "as-is". There's no compilation step available when including web components. So the transpilation (incl. polyfills) needs to be done in advance, before publishing the web component. That's why it's a `devDependency`. – AxD Feb 18 '19 at 20:40