组件样式网址在生产构建中不起作用 角度



我最近将我的一个项目从 10 更新到 Angular 13,在开发过程中一切正常。然后,当我生成生产版本时,注意到存在样式问题。经过一些调查,我发现问题与styleUrls不知何故不阅读样式表链接有关。我找到了这篇文章和这篇文章,更像是他们提供了一些解决方法,而不是解决方案和为什么会发生这种情况的细节。我只尝试了建议的修复程序之一,因为大多数看起来都不像可行的解决方案。

我尝试了require方法; 用styles替换styleUrls然后需要样式表,以便require('home.component.css')它可以工作,但是我的样式scss并且我的项目非常大,我需要永远将所有styleUrls更新为styles

有没有人知道为什么会发生这种情况以及解决方法是什么?

开发服务器中没有问题,仅在生成最终构建时

示例代码,与更新(Angular 10 -> 13)相比没有太大变化,我想不出任何其他代码可以提供帮助。

Home.component.ts

import { Component, OnInit } from '@angular/core';
//...
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'], // <-- problematic
// styles: [require('home.component.css')] // works, notice the ext change I have css file to go along
})
export class HomeComponent implements OnInit {
//...
constructor(/** ... */) {}
ngOnInit(): void {
//...
}
//...
}

首页.组件.html

<div class="container">
<!-- ... -->
</div>

Home.component.scss

.container {
width: 100%;
height: 100%;
background-color: red;
/* ... */
}

在开发ng serve,我可以看到红色背景

在生产ng buildng build --configuration production --aot我看不到它,它默认为白色

我把这个项目放在一边,直到几天前,当我在处理另一个项目时得到了解决方案的提示时。从 Angular 10 到 13,Angular 工作区配置,angular.json,发生了一些变化(实际上是从 v11 开始),这就是它让我得到的地方。我将嵌套属性optimization(请参阅下面的 v10 代码)设置为trueproduction环境中,在development下设置为false.设置为true它对脚本和样式以及自 v11 以来对字体执行了一系列优化。 v10 上的styles只是一个布尔属性,当设置为true时,会缩小样式。从 v11 开始,styles也可以是具有布尔属性minify&inlineCritical的对象。默认情况下,它们设置为true。就我而言,问题出在inlineCritical上,所以我将其设置为false(请参阅下面的 v13 代码)。

这不是一个可靠的解决方案,因为旨在"提升"性能的优化选项正在关闭。我将继续调查为什么会发生这种情况并发布任何更新。

简化angular.jsonv10

{
"projects": {
"app_name": {
"architect": {
"build": {
"configurations": {
"production": {
"optimization": true // <=== The issue 
},
"development": {
"optimization": false
}
}
}
}
}
}
}

简化angular.jsonv13

{
"projects": {
"app_name": {
"architect": {
"build": {
"configurations": {
"production": {
"optimization": {
"styles": {
"inlineCritical": false // <=== The fix
}
}
},
"development": {
"optimization": false
}
}
}
}
}
}
}

其他上下文; 这个项目使用 Bootstrap 进行样式设置,另一个给我提示的项目是使用 Tailwind;我对两者都有同样的问题。

最新更新