精致的全球风格

问题描述

我正在使用lit-element(Typescript)开发Web组件,并且想要创建一些CSS文件来为我的Web组件包定义一个“全局主题”。

我在磁盘上的结构是这样的:

?src

┣?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]; }