关于angular:Angular-项目中导入-styles-文件到-Component-中的一些技巧

5次阅读

共计 1631 个字符,预计需要花费 5 分钟才能阅读完成。

家喻户晓,咱们应用 Angular CLI 创立 Component 之后,每个 Component 都会有本人的专属 styles 文件。通常状况下,也存在另一种可能性,即可能须要在组件中蕴含全局 (global) 款式文件(尤其是变量文件,即 variable files)。
假如在 src/stylings 文件夹下有一个文件:_variables.scss:

其内容如下:
// your _variables.scss file
$brand-color: #800000;
复制代码
咱们的 Component 模板文件:
<!– hello.component.html –>
<h1>
Hello World!
</h1>
复制代码
Component 的 style 文件:
// hello.component.scss
@import “../../../stylings/variables”; // this is not cool!

h1 {

color: $brand-color;

}
复制代码
下面代码里呈现的层级构造操作符,../, 意思是当前目录的父目录,这种写法可读性不好,且容易出错。
如果您的我的项目是应用 Angular CLI 生成的,您能够在 .angular.cli.json 文件中增加配置 stylePreprocessorOptions > includePaths。此配置容许开发人员增加将查看导入的额定根本门路。它通知 Angular CLI 在解决每个组件款式文件之前,在上述门路中查找款式文件。
例如,在咱们的例子中,让咱们在门路中增加 ./stylings。因为配置承受数组类型,因而咱们能够增加多个门路。
{

...
"apps": [{
    "root": "src",
    ...
    "stylePreprocessorOptions": {
        "includePaths": ["./stylings"]
    }
    
}]

}
复制代码
留神,在高版本的 Angular 我的项目里,上述配置位于文件 angular.json 内:

“stylePreprocessorOptions”: {

          "includePaths": [
            "./projects",
            "./projects/storefrontstyles/scss",
            "./feature-libs"
          ]
        },

复制代码
当初,咱们能够批改咱们的 Component Style 文件了:
// hello.component.scss
@import “variables”; // change to just variables, say goodbye to ../../../stylings/

h1 {

color: $brand-color;

}
复制代码
如果咱们有两个同名的 global style 文件,然而位于不同的目录下,则又该如何配置?
例如咱们具备如下的层级构造:

_variables.scss 文件的内容:
// stylings2/_variables.scss
$brand-color: blue;
$font-size-large: 40px;
复制代码
将这个 scss 文件所在的目录,stylings2 也增加到 includePaths 数组内:

更新组件本人的 scss 文件:
// hello.component.scss
@import “variables”;

h1 {

color: $brand-color;
font-size: $font-size-large;

}
复制代码
刷新利用,遇到谬误音讯:undefined variable. 尽管 stylings2 文件夹里蕴含的 variables.scss 文件里,的确定义了变量 $font-size-large,但无奈被我的项目正确解析到。
事实证明,如果有多个同名文件,Angular CLI 将只抉择第一个匹配名称的文件。在这种状况下,它将抉择 ./stylings 文件夹下的 _variables.scss 文件。这就是它无奈获取变量 $font-size-large 的起因,因为这个变量定义在 styling2/_variables.scss 文件中。

正文完
 0