【问题标题】:How to import css inside typescript如何在打字稿中导入css
【发布时间】:2019-08-08 19:04:09
【问题描述】:

我有一个全局 css 文件,我在其中定义了所有颜色。我试图在打字稿中导入该值,但它不起作用。这是我最后一次尝试:

get sideWindowStyle(): any {
    switch (this.windowStyle) {
      case 'classicStyle': {
        return {
          '@import' : 'src/styles-library/colors-variables.scss',
          'background-color': '$primary-lightest-color'
        };
      }
      case 'lightStyle': {
        return {
          'background-color': '#ffffff'
        };
      }
      default: {
        return {
          'background-color': '#f1f9fe'
        };
      }
    }
  }

没有导入或使用它仍然无法正常工作。

【问题讨论】:

  • Scss 文件被转译成 css 并且在运行时不可用。无论如何,您不能以这种方式更改 css 文件。
  • 你检查我的答案了吗?????? ?
  • 这是设置视图样式的错误方式。你应该只玩 CSS。 TS 不负责处理视图,而是负责处理逻辑。阅读 scss 中的 @host

标签: angular typescript sass


【解决方案1】:

在构建期间将其转译为 css,然后将该文件链接到您的 index.html 文件中:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="dist/colors-variables.css">
</head>
<body>
</body>
</html>

【讨论】:

    【解决方案2】:

    sass 变量将在构建 ant 期间编译,在运行时将无法访问,因此您可以使用 css 变量?

    style.scss

    :root {
      --primary-lightest-color: brown;
    }
    

    sideWindowStyle

    get sideWindowStyle(): any {
        switch (this.windowStyle) {
          case 'classicStyle': {
            return {
              'background-color': 'var(--primary-lightest-color);'
            };
          }
          case 'lightStyle': {
            return {
              'background-color': '#ffffff'
            };
          }
          default: {
            return {
              'background-color': '#f1f9fe'
            };
          }
        }
      }
    

    CSS variables MDN ?

    【讨论】:

      【解决方案3】:

      如果 window.style 是模板中的一个类,那么您可以使用 Host 实现所需的样式:

      :host(.classicStyle) { 'background-color': '$primary-lightest-color' }
      :host(.lightStyle) { 'background-color': '#ffffff' }
      background-color: '#f1f9fe'
      

      如果这两个类中的任何一个在您的元素的容器中,这段代码将自动更改您的 background-color 属性。

      如果 window.style 是 TS 对象,则根据其值,将宿主元素的类更改为 classicStylelightStyle,然后给定的 host 代码将起作用。

      【讨论】:

        猜你喜欢
        • 2022-07-28
        • 2017-07-31
        • 2021-07-23
        • 2020-04-18
        • 2017-02-19
        • 2021-08-14
        • 2018-10-21
        • 2018-05-24
        • 2019-02-21
        相关资源
        最近更新 更多