Angular 项目中导入 styles 文件到 Component 中的一些技巧
【摘要】 本文介绍笔者在实际 Angular 项目中学习到的如何将全局 styles 文件应用到 Component 的开发技巧。
本文介绍笔者在实际 Angular 项目中学习到的如何将全局 styles 文件应用到 Component 的开发技巧。
众所周知,我们使用 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 的值修改成 styling
和 styling2
两个文件夹的父文件夹。
{
...
"apps": [{
"root": "src",
...
"stylePreprocessorOptions": {
"includePaths": [
"."
]
}
}]
}
然后 Component 的 scss 文件修改成如下,直接相对于 styling
和 styling2
的父文件夹路径进行引用:
// hello.component.scss
@import "stylings/variables";
@import "stylings2/variables";
h1 {
color: $brand-color;
font-size: $font-size-large;
}
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)