【问题标题】:Angular 4 - Read the rules by name from scss fileAngular 4 - 从 scss 文件中按名称读取规则
【发布时间】:2019-02-15 22:45:18
【问题描述】:

我需要通过类选择器从 .scss 文件中提取规则,以显示在 Angular 应用程序 ui 上,但到目前为止还没有找到一个好的 .scss 解析器,我可以使用它来按名称获取类规则。

示例:如果我通过类选择器名称='custom-class',我需要括号中的内容,很简单。

.custom-class {
   width: 334px;
   text-decoration: underline;
}

是否有可以使用的 scss 类型?或者任何可以使用的 npm 包,我可以提供文件路径和必须从 scss 文件中读取规则内容的类名? 列出类选择器的示例(https://www.npmjs.com/package/list-css-selectors)有一个 npm 包(但适用于 css 文件),但找不到可以从 scss 文件中获取类内容的包。

【问题讨论】:

    标签: angular typescript sass


    【解决方案1】:

    您无法从应用程序运行时访问 .scss 文件,因为它们被处理为 css 文件。您可以尝试列出浏览器加载的所有样式表以找到所需的类。

    for (let i = 0; i < document.styleSheets.length; i++) {
      const sheet = document.styleSheets[i];
      if (sheet['cssRules']) {
        for (const rule of sheet['cssRules']) {
          const cssText = rule['cssText'] as string;
          if (cssText.startsWith('.my-class')) {
            console.log(cssText);
          }
        }
      }
    }
    // Console output:
    // .my-class { color: rgb(51, 51, 51); }
    

    【讨论】:

    • @Vinc 如果我的回答有用的话,你可以投票或接受我的回答吗?
    • 感谢您的回复Dmitriy,甚至在样式进入浏览器之前,我必须获取,所以目前采用在UI CSS而不是SCSS中显示的方法,我找到了这个包@987654321 @,它给出了 CSS 文件的 JSON 格式,请建议是否有更好/有效的解决方案?
    猜你喜欢
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2018-04-10
    相关资源
    最近更新 更多