带 litelement 的全局样式

Global Styles with litelement

我正在使用 lit-element (Typescript) 开发网络组件,我想创建一些 css 文件来为我的网络组件包定义“全局主题”。

我的磁盘结构是这样的:

┣css

┃ ┣ color.css.ts

┃ ┗ size.css.ts

┣button.css.ts

┣WCButton.ts

┗WcTheme.ts

让我解释一下:

  1. Css 文件夹将包含用于声明默认值的单独文件(在此示例中为颜色和大小):
import { css } from "lit-element";

export const defaultColor = css`
    .primary{
        background: #356e3b;
    }
    .secondary{
        background: #5b8e48;
    }
    .terciary{
        background: #302e2b;
    }
`;

(color.css.ts 代码)

  1. WcTheme.ts文件就是把css文件夹里面的文件整合成一个文件:
import { defaultSize } from './css/size.css';
import { defaultColor } from './css/color.css';

import { LitElement } from 'lit-element';

export class WcTheme extends LitElement {
  static styles = [defaultColor, defaultSize];
}
  1. button.css.ts 是具体组件(在本例中为按钮)的 CSS 规则
import { css } from "lit-element";

export const buttonStyles = css`
  .btn-default {
      border: 1px solid lime;
  }
  1. WcButton.ts是web组件(按钮)的代码定义
import { LitElement, html } from 'lit-element';

import { WcTheme } from './WcTheme';
import { buttonStyles } from "./button.css";

export class WcButton extends LitElement {

  static get styles() {
    return [WcTheme.getStyles(),buttonStyles];
  }

  public render() {

    return html`
      <button
        type="button"
        class="btn-default"
      >
        <span class="primary h1">Test</span>
      </button>
    `;
  }
}

此结构抛出下一个错误:

[tsc] src/WCButton.ts(6,14): error TS2417: Class static side 'typeof WcButton' incorrectly extends base class static side 'typeof LitElement'.
[tsc]   Types of property 'styles' are incompatible.
[tsc]     Type '(CSSResult | CSSStyleSheet | CSSResultArray | undefined)[]' is not assignable to type 'CSSResult | CSSStyleSheet | CSSResultArray | undefined'.
[tsc]       Type '(CSSResult | CSSStyleSheet | CSSResultArray | undefined)[]' is not assignable to type 'CSSResultArray'.
[tsc]         The types returned by 'concat(...)' are incompatible between these types.
[tsc]           Type '(CSSResult | CSSStyleSheet | CSSResultArray | undefined)[]' is not assignable to type '(CSSResult | CSSStyleSheet | CSSResultArray)[]'.
[tsc]             Type 'CSSResult | CSSStyleSheet | CSSResultArray | undefined' is not assignable to type 'CSSResult | CSSStyleSheet | CSSResultArray'.
[tsc]               Type 'undefined' is not assignable to type 'CSSResult | CSSStyleSheet | CSSResultArray'.
[tsc]
[tsc] 22:12:09 - Found 1 error. Watching for file changes.

因为我可以整合 WcTheme.ts 创建的 CSSResultArray 和 button.css.ts 创建的 CSSResult。

谁能帮我解决这个问题,或者是更好的解决方案?

提前致谢。

我已经用相同的文件结构解决了这个问题,在 WcButton.ts 中我已经更改:

static get styles() {
    return [WcTheme.getStyles(), buttonStyles]; }

static get styles() {
    return [...WcTheme.styles, buttonStyles]; }