【问题标题】:Angular2+Webpack , loads styles twice at the headAngular2+Webpack ,在头部加载样式两次
【发布时间】:2016-09-19 09:22:03
【问题描述】:

我正在尝试将 Universal + webpack 与 Angular2 一起使用。 但我不明白为什么样式会在 head 元素处加载两次。

这是我从那里分叉的 git 存储库,我没有改变任何东西! https://github.com/angular/universal-starter.git

我可以在这里写代码,但它会变得一团糟。

下面是我的控制台截图,显示了相同的样式被加载了两次:

谁能解释一下 Angular2 在 css 中的表现?

提前致谢。

【问题讨论】:

  • 我也有同样的问题...
  • 我遇到了这个问题,并通过将ViewEncapsulation.None 更改为Default 或其他方式解决了这个问题。除了None.
  • 我遇到了这个问题,但想在 app.component.ts 中将 ViewEncapsulation 设置为 None,结果认为我在我的应用程序的 stylesUrls 中引入了高级样式表 (LESS)零件。一旦我把它拿出来并让 webpack 为我打包它,我就不再到处都有重复的样式了。

标签: angular webpack


【解决方案1】:

我没有查看 repo(我对最后的问题有一个假设),但回答了你关于 angular 如何处理 css 的问题:

有多种方法可以将样式插入到您的角度

样式插入

1- 组件内联样式

@Component({
    selector: 'sample',
    styles: [`
        p {
            color: #999;
        }'],
    template: '<p>Hello World</p>'
})

2- 外部样式表

@Component({
    selector: 'sample',
    styleUrls: ['./styles.css'],
    template: '<p>Hello World</p>'
})

3- 模板内联样式

@Component({
    selector: 'sample',
    template: `
        <style>
            p {
                color: #888;
            }
        </style>
        <p>Hello World</p>
    `,
})

在这 3 种方法中,您所有的样式都将放在生成的 html 的头部。

4- Html 内联样式

@Component({
    selector: 'sample',
    template: '<p style="color: #999;">Hello World</p>'
})

样式将保留在标签中,并且只会应用于组件的这个特定部分

查看封装

对于前 3 种类型,根据 封装,样式要么应用于整个应用程序,要么仅应用于一个组件

ViewEncapsulation.None angular 2 没有什么特别的操作

ViewEncapsulation.Native Angular 2 使用影子 DOM 的思想,并将这些样式仅应用于它的组件

ViewEncapsulation.Emulated The default view encapsulation Angular 2 试图通过在组件的内容中添加一些标识类并对它们进行样式化(.成功消息[_ngcontent-usm-6] {...} )

应用视图封装

import {ViewEncapsulation} from @angular/core;

@component({
   selector: ...
   template: ...
   styles: ... (or styleUrls)
   encapsulation: ViewEncapsulation.None,
})

我的假设

您可能会发现样式包含在两个不同的组件中。

【讨论】:

    猜你喜欢
    • 2015-11-04
    • 1970-01-01
    • 2015-10-09
    • 2019-06-16
    • 1970-01-01
    • 2016-03-06
    • 2017-07-31
    • 2017-11-06
    • 2016-02-23
    相关资源
    最近更新 更多