问题描述
默认情况下,Angular 2 将 CSS 编译为 JavaScript,尤其是在像 Angular-CLI 一样使用 WebPack 时.出于几个原因,我宁愿这不会发生.
By default, Angular 2 compiles the CSS into JavaScript, especially when using WebPack as in Angular-CLI. I would rather this not happen for a couple of reasons.
第一个原因是,当我进行开发时,我发现能够在开发人员工具中准确查看特定样式规则来自哪个样式表以及它在哪个行号上确实很有帮助.第二个原因是我认为将 CSS 编译成代码有点忽略了好的 CSS 的要点,即您可以应用不同的样式表,并使用相同的标记获得完全不同的外观.
The first reason is that when I'm developing, I find it really helps to be able to see in the developer tools exactly what style sheet a specific style rule was coming from and what line number it was on. The second reason is that I think compiling CSS into the code kind of misses the point of good CSS, which is that you can apply a different style sheet and have an entirely different look and feel with the same markup.
是否有一个标志可以设置为将 CSS 保留在 .css 文件中,IMO 所属的位置?
Is there a flag somewhere that I can set to leave the CSS in .css files, where IMO it belongs?
推荐答案
这就是封装组件的全部意义.
This is the whole point of encapsulated components.
组件应该封装自己的样式,以便随样式一起提供.
A component should have it's own styles encapsulated with it so it can be shipped with the styles.
想象一下,你想发布你的一个组件供其他人使用,它不应该有自己的样式吗?
Imagine you want to publish one of your components to be used by others, shouldn't it have its own styles with it ?
这意味着 Angular 需要一种方法将这些 css 链接到组件,从而将它们分成块并将它们注入到 head 标记中.
That means Angular needs a way to link those css to the component , thus seperates them into chunks and injects them into head tag.
不过,要解决您的问题,您有几个选择:
To solve your problem though , you have couple of options :
1- 不使用模拟封装:
1- Not using the Emulated Encapsulation :
组件默认有一个名为 encapsulation 的属性设置为 Emulated ,您需要将其更改为 None :
Components by default have a property called encapsulation which is set to Emulated , you need to change it to None:
@Component({
encapsulation:ViewEncapsulation.None
})
然后,您可以像处理普通 html 页面一样将所有 css 放在自己的 head 标签中.
Then , you can put all you css in the head tag your self like you'd do with a normal html page.
2- 如果问题是主题化,您可以使组件主题化.
2- If the problem is theme ing , you can make your component themeable .
您可以为组件设置主题属性,然后根据该属性更改样式:
You can have a theme attribute for your component and then based on that change the styleing :
@Component({
selector:'my-component',
styles:[
`
:host{
[theme="blue"]{
change what ever you want :
h1{
color:blue;
}
}
}
`
]
})
然后,使用这个组件就像:
And then , using this component would be like :
<my-component [attr.theme]='"blue"'></my-component> // would be blue theme
<my-component></my-component> // would be default
这篇关于在 Angular 2/Angular-CLI 中将 CSS 排除在 JS 之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!