Stenciljs CSS 全局变量

Stenciljs CSS global variables

我无法让全局 css 变量按照离子模板 docs 中的描述工作。

我在 'src/global/' 中创建了一个 'variables.css' 文件,然后将 "globalStyle: 'src/global/variables.css'" 放入 "stencil.config.ts" 文件中。

然后我在 variables.css 中创建了一组 css 变量,并试图在我的组件的 css 文件中使用它们;但是,使用默认值,因为它无法加载全局变量。

// stencil.config.ts
import { Config } from '@stencil/core';

export const config: Config = {
    namespace: 'mycomponent',
    outputTargets:[
        {
            type: 'dist'
        },
        {
            type: 'www',
            serviceWorker: null
        }
    ],
    globalStyle: 'src/global/variables.css'
}


// src/global/variables.css
:root {
    --qa-primary-color: #2169e7;
    --qa-secondary-color: #fcd92b;
    --qa-dark-color: #0000;
    --qa-light-color: #ffff;
    --qa-font-family: Arial, Helvetica, sans-serif;
    --qa-font-size: 12px;
}


// src/components/my-component.css
.main {
    background: var(--qa-dark-color, yellow);
}
.first {
    color: var(--qa-primary-color, pink);
}
.last {
    color: var(--qa-secondary-color, green);
}

有空可以看一下测试repo

我自己实现了这个功能,使用 copy config 将我的 global/variables.css 从 src/ 目录复制到 www/ 和 dist/。此外,为了测试,我在 index.html 文件中为 global/variables.css 添加了样式表 link 标记。如果您遵循此流程,则无需设置 globalStyle 配置。

虽然这没有解决 docs 中描述的过程似乎不正确的事实,但它确实提供了预期的效果。

// stencil.config.ts
import { Config } from '@stencil/core';

export const config: Config = {
  namespace: 'mycomponent',
  outputTargets:[
    {
      type: 'dist'
    },
    {
      type: 'www',
      serviceWorker: null
    }
  ],
  copy: [
    { src: 'global' }
  ]
}

// html.index
<!DOCTYPE html>
<html dir="ltr" lang="en">
    <head>
        ...
        <link rel="stylesheet" type="text/css" href="global/variables.css">
    </head>
    <body>
        ...
    </body>
</html>

我通过将 <link rel="stylesheet" href="/build/{YOUR_NAMESPACE}.css"> 添加到 src/index.html 来解决这个问题。

如果您使用的是 SASS,那么您可以将其添加到 stencil.config.ts 文件中

...   
plugins: [
    sass({
      injectGlobalPaths: ["src/global/variables.scss"]
    })
  ]
...

这个问题是由于阴影 DOM 在使用 @component 装饰器时我们有一个 属性 阴影使它错误。这应该在嵌套组件中遵循。参考 https://stenciljs.com/docs/styling#shadow-dom

@Component({
  tag: 'to-do-card-list',
  styleUrl: 'to-do-card-list.css',
  shadow: false,
})

Refer image