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

3次阅读

共计 1928 个字符,预计需要花费 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 文件中。

解决方案

将 angular.json 里 includePaths 的值批改成 stylingstyling2 两个文件夹的父文件夹。

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

而后 Component 的 scss 文件批改成如下,间接绝对于 stylingstyling2 的父文件夹门路进行援用:

// hello.component.scss
@import "stylings/variables";
@import "stylings2/variables"; 

h1 {
    color: $brand-color;
    font-size: $font-size-large;
}
正文完
 0