Adding lit-element and lit-html to a global variabel

1.2k views Asked by At

I have several lit-elements on my page, but I can't compile them all together so I would like to "share" the lit stuff through a global variable. Might be a bit unconventional, but right now it will save me a lot of bytes.

I'm using rollup to do the packaging.

I think I'm pretty close to achieve what I want, but there is something that I'm missing...

This is my component..

@customElement('tab-strip')
export class TabStrip extends LitElement {

Resulting in


var tabstrip = (function (exports, litElement, repeat, classMap) { 
//SOME OTHER STUFF

  exports.TabStrip = class TabStrip extends litElement.LitElement {...
.
.
.
${repeat.repeat(this._tabs, e => litElement.html
  

}({}, Globals, Globals.repeat, Globals.classMap))

I have create a Globals.ts file that looks like this..

import { customElement, html, LitElement, property } from "lit-element";
import { Template, TemplateResult } from "lit-html";
import { classMap } from "lit-html/directives/class-map";
import { repeat } from "lit-html/directives/repeat";

class Globals {
    public html = html;
    public LitElement = LitElement;
    public customElement = customElement;
    public property = property;
    public repeat = repeat;
    public classMap = classMap;
    public Template = Template;
    public TemplateResult = TemplateResult;

}
window["Globals"] = new Globals();

And at last my rollup.config

input: inputDir + name + ".ts",
output: {
    file: outputDir + name + ".js",
    name: name,
    format: format,
    sourcemap: true,
    globals: {
        "lit-element": "Globals",
        'customElement': 'Globals.customElement',
        'lit-html': "Globals.LitHtml",
        'html': "Globals.html",
        'property': "Globals.property",
        'lit-html/directives/repeat': "Globals.repeat",
        'lit-html/directives/class-map': 'Globals.classMap',
        'Template': 'Globals.Template',
        'TemplateResult': 'Globals.TemplateResult'
    }
},
plugins: [
    typescript({
        experimentalDecorators: true
    }),
    resolve(),
    // terser({"ecma":"2019"}),
],
external: ['lit-element', 'lit-html', "lit-html/directives/repeat", "lit-html/directives/class-map"]

Gut feeling is that I have misunderstood something in the external stuff of rollup.. AS you can see in the generated file it says litElement.LitElement instead of just litElement

Any help??

1

There are 1 answers

0
Justin Formentin On

Does it work for you? This seems correct just taking it at face value.

Looking at what your Globals is, it's an object with the properties LitElement, property, html, and so on.

If we look at your tabstrip function, the second argument is litElement, which matches the Globals Object being passed in.

So class TabStrip extends litElement.LitElement

makes sense, since the litElement is referencing your Globals object, and that has the LitElement property.