在angular 2组件中访问bootstrap scss变量 [英] Accessing bootstrap scss variables in angular 2 component
问题描述
我正在使用Angular CLI构建一个新的Angular2项目,并将该项目配置为使用SCSS.我已将Bootstrap 4成功加载到我的styles.scss
文件中,但是,如果尝试访问任何Bootstrap的文件(或从某个组件中的styles.scss
中定义的我自己的变量,则会得到Undefined Variable
生成错误.
I'm working on a new Angular2 project built using Angular CLI and have configured the project to use SCSS. I have Bootstrap 4 successfully loaded into my styles.scss
file however if I try and access any of Bootstrap's (or my own variables defined in styles.scss
from within a component I get Undefined Variable
build error.
在angular-cli.json
的styles
节点中,在主条目之前编译的组件的样式文件吗?我如何才能使在全局级别定义的任何变量可用于应用程序中的所有组件?谢谢!
Are the style files for components compiled before the main entry in the styles
node of angular-cli.json
? How can I make is so that any variables defined at that global level are available to all components in the application? Thanks!
angular-cli.json
"apps": [
{
...
"styles": [
"styles/styles.scss"
],
...
}
]
styles.scss
// Bootstrap
$enable-flex: true; // Enable Flexbox mode
@import "../../node_modules/bootstrap/scss/bootstrap";
组件
.navbar {
background: $brand-primary; // Undefined variable here
}
推荐答案
仅因为要将引导程序4导入到styles.scss
中并不意味着组件上的.scss
文件可以访问该文件.
Just because you are importing the bootstrap 4 into your styles.scss
doesn't mean your .scss
files on your components have access to that.
在您的component.scss
上,您必须导入Bootstrap变量:
On your component.scss
you have to import the Bootstrap variables:
@import '~bootstrap/scss/_variables.scss';
.navbar {
background: $brand-primary; // No more Undefined variable here
}
说明
在我看来,很多人对此感到困惑,您不应该将bootstrap.scss
导入到组件中,而应该只导入所需的东西.
Explanation
A lot of people seem to me confused by this, you should not import bootstrap.scss
to your components you should only import the things that you need.
如果您仔细查看 bootstrap.scss的源代码他们将所有内容分隔在不同的文件中.您具有mixins
文件夹和_variables.scss
文件.这些应该是您在组件上导入的唯一内容,以避免CSS重复.
If you look closely into the source code of bootstrap.scss they have everything separated in different files. You have the mixins
folder and the _variables.scss
file. Those should be the only things you import on your component to avoid CSS duplication.
这会增加我的捆绑包大小,将这些东西导入每个组件吗?
Would this increase my bundle size, importing these things on every component?
不,不会.为什么? mixins
和variables
是特定于sass的(至少现在是这样),因此,当您将所有变量这样导入到组件中时:
No, it won't. Why? mixins
and variables
are sass specific (at least for now) so when you import all the variables into your component like this:
@import '~bootstrap/scss/_variables.scss';
.navbar {
background: $brand-primary;
}
其输出CSS将是:
.navbar {
background: #007bff;
}
编译为CSS后,其余变量将被丢弃.
The rest of the variables will be discarded after compiling to CSS.
这篇关于在angular 2组件中访问bootstrap scss变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!