runem / lit-analyzer

Monorepository for tools that analyze lit-html templates
MIT License
317 stars 36 forks source link

[Feature Request] Is it possible to support custom decorators (encapsulation of @customElement) #268

Open hungtcs opened 2 years ago

hungtcs commented 2 years ago

Hallo,

I'm using webpack to handle the import of styles (lit-css-loader: it returns a CSSResult), to simplify usage, I created a custom decorator, it helped me to automatically add styles to the styles static property and then call customElement to register the element.

Unfortunately, the plugin are not well supported, I can't get tips like no-missing-element-type-definition, is it possible to add a config field to help the plugin identification the custom-element.

Thanks.

import style from './app.element.scss';
import { Component } from '@shared/decorators';
import { html, LitElement } from 'lit';

@Component({
  styles: [style],
  tagName: 'hello-world',
})
export class HelloWorldElement extends LitElement {

  protected render() {
    return html`
      <div>
        <h1>hello world!</h1>
      </div>
    `;
  }
}
import { CSSResult } from 'lit';
import { customElement } from 'lit/decorators.js';

export interface ComponentOptions {
  styles?: Array<CSSResult>;
  tagName: string;
}

export function Component(options: ComponentOptions): ClassDecorator {

  return (target) => {
    if (options.styles) {
      const _styles = Array.isArray(options.styles) ? options.styles : [options.styles]
      const targetStyles = (target as any).styles ?? [];
      const styles: Array<CSSResult> = Array.isArray(targetStyles) ? targetStyles : [targetStyles];
      styles.push(..._styles);
      (target as any).styles = styles;
    }

    customElement(options.tagName)(target);
  };
}