Search code examples
javascripttypescriptpolymerweb-componentlit-element

Polymer not loading ts web component with polymer serve


Following the LitElement guide here: https://lit-element.polymer-project.org/guide/start

I'm literally following it by the books and then running polymer serve in the root directory of the project.

I even copy/pasted over every file from their example stackblitz pages. Am I not supposed to use polymer serve or something?

All I get is blank page, and it seems to not recognize the customElement

Nothing created under my-element

my-element.ts:

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

@customElement('my-element')
export class MyElement extends LitElement {
  @property()
  foo = 'foo';

  render() {
    return html`
      <p>hi!</p>
    `;
  }
}

index.ts:

import './my-element.ts';

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <script src="/node_modules/@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js"></script>
    <script src="/node_modules/@webcomponents/webcomponentsjs/webcomponents-bundle.js"></script>

    <title>lit-element code sample</title>
  </head>
  <body>
    <my-element></my-element>
  </body>
</html>

package.json:

{
  "name": "my-app",
  "version": "1.0.0",
  "license": "ISC",
  "dependencies": {
    "@webcomponents/webcomponentsjs": "^2.2.10",
    "lit-element": "^2.1.0"
  }
}

Solution

  • I even copy/pasted over every file from their example stackblitz pages

    Actually Stackblitz TS projects follow a particular structure in which index.ts is treated as the entry point of the TypeScript code, automatically compiled and imported in the final result.

    The local scenario is pretty different: you have to choose a build tool to compile TS files and import the result in index.html:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <!-- ... -->
        <!-- This may differ depending on your build configuration -->
        <script src="./path/to/my-element.js" type="module"></script>
      </head>
      <body>
        <my-element></my-element>
      </body>
    </html>
    

    You can use tsc directly or a module bundler such as Webpack + ts-loader or Rollup + rollup-plugin-typescript2. This really depends on the complexity and requirements of your projects and what browsers you want to support.