Don Chambers
Don Chambers

Reputation: 4251

How do I consume a polymer lit-element?

I have a litElement that I will need to consume from another domain. My browser is Chrome, I am using 'polymer serve' and navigating directly to the es5-bundle.

The lit-element is very simple. Just some static text.

When I use 'polymer build' my entry HTML page gets compiled (or transformed). I see a reference to 'custom-elements-es5-adapter.js' is added, as well as other custom JavaScript. When I navigate to this entry page (in the build folder) everything works. However, if I replace that compiled version with the original uncompiled version I get an error in the chrome console 'define is not defined'.

Eventually I will be calling this from another domain and will not be building the HTML it with polymer.(I have already tried it cross-domain and it's not working)

What do I need to include in the client to consume the polymer lit-element?

Here is what I have:

<body>
    <my-element></my-element>
    <script src="../node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
    <script type="module" src="./components/my-element.js" crossorigin=""?</script>
</body>

Upvotes: 0

Views: 1562

Answers (1)

Kate Jeffreys
Kate Jeffreys

Reputation: 559

lit-element requires a transform step. The files the browser consumes must be transformed. If you want to deploy your original source files, the web server to which you deploy them needs to perform the transform step itself (as polymer serve does).

Source: lit-element README:

LitElement is published on npm using JavaScript Modules. This means it can take advantage of the standard native JavaScript module loader available in all current major browsers.

However, since LitElement uses npm convention to reference dependencies by name, a light transform to rewrite specifiers to URLs is required to get it to run in the browser. The polymer-cli's development server polymer serve automatically handles this transform.

Tools like WebPack and Rollup can also be used to serve and/or bundle LitElement.

The lit-element README has an example that will run in a browser with no transform steps. The example loads the lit-element library as modules from unpkg like this:

<script type="module">
  import {LitElement, html} from 'https://unpkg.com/@polymer/lit-element@latest/lit-element.js?module';
  class MyElement extends LitElement {

  ...
</script>
<my-element></my-element>

That method is useful if you want to try out lit-element with less messing about, but the Polymer team doesn't recommend doing this in production; AFAIK unpkg has no guarantees about uptime or performance.

Upvotes: 1

Related Questions