LoginSignup
7

More than 5 years have passed since last update.

posted at

updated at

Vanilla JS や TypeScript で Custom Elements を書く際の注意点

Vanilla JS や TypeScript を使って Web Components の Custom Elements を書いてビルドした結果、ブラウザのコンソールに

Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

というエラーが出ることがあります。

原因

Custom Elements が ES5 形式のコードになってしまっているのが原因です。

仕様では、Custom Elements は ES6 の class 構文である必要があります。しかし、ビルド時に TypeScript や Babel を通すことで、意図せず ES5 形式のコードになってしまっていることがあります。この時、上記のエラーが出ます。

チェックポイント

TypeScript を使っている場合

Compiler Options の --target"ES6" になっているか確認します。

tsconfig.json
{
  "compilerOptions": {
    "target": "ES6"
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

Babel を使っている場合

Babel でトランスパイルをすると ES5 形式のコードになってしまいますが、babel-plugin-transform-custom-element-classes を併用することで上記のエラーを回避することができます。

{
  "presets": ["env"],
  "plugins": ["transform-custom-element-classes"]
}

ES5 形式のコードをそのまま使いたい場合

ES6 をサポートしていないブラウザも対象にする必要があるなど、ES5 形式のコードをそのまま使いたいというケースもあるかと思います。

この場合、Custom Elements を宣言する前に custom-elements-es5-adapter.js という polyfill を読み込むと、 ES5 形式の Custom Element を正常に動かすことができます。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
7