【问题标题】:Angular 8 CSS doesn't load on refresh, production buildAngular 8 CSS 不会在刷新、生产构建时加载
【发布时间】:2021-06-24 01:17:59
【问题描述】:

我的 index.html 看起来像这样:

<!doctype html>
<html lang="hu">
<head>
  <meta charset="utf-8">
  <title>WebsiteName</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
<!-- etc -->

当我使用“ng build”时代码运行良好,但是当我在生产模式下编译它时(使用“ng build --prod”)它似乎运行良好,但重新加载时会禁用 style.css。

更新:@Elizaveta 的回答是正确的,但新问题是

  <link rel="stylesheet" href="styles.d42b9ef58619804546db.css">

由“ng build --prod”生成,如下所示:

<link rel="stylesheet" href="styles.d42b9ef58619804546db.css"><!doctype html>
<html lang="hu">
<head>
  <meta charset="utf-8">
  <title>Nebulónia</title>
  <base href="/">

<!-- etc -->

我如何告诉 Angular 在哪里生成它?

这里是完整的 github 仓库:https://github.com/lori2001/NebuloniaWebsite

【问题讨论】:

  • 你的 basehref 真的应该是 / 吗?换句话说,您的页面在mydomain.commydomain.com/somepath 是否可见?
  • 它必须是“/”,因为我正在使用语言的路由参数,否则它似乎不起作用=D。过去我有“./”,它确实工作得很好

标签: angular typescript routes page-refresh


【解决方案1】:

这是因为您需要关闭 src/index.html 文件中的 &lt;head&gt; 标记

<!doctype html>
<html lang="hu">
<head>
 <meta charset="utf-8">
 <title>Nebulónia</title>
 <base href="/">
 <!-- all your meta here -->
 <meta name="theme-color" content="#ff7e00">
 </head> <!-- Make sure to close the head tag -->
 <body>

说明

在 prod 模式下构建将使用 angular.json 文件中的 production 配置,该文件将 extractCss 设置为 true

 "configurations": {
        "production": {
          // ...
          "sourceMap": false,
          "extractCss": true,

这将导致您的应用程序中的所有 css 样式被提取到 styles.xyz.css 文件中,该文件会在 head 标签关闭之前尝试注入。由于它没有在您的 index.html 文件中关闭标签,因此构建过程会将 css 链接添加到文件顶部。

在开发模式下,extractCSS 设置为 false(角度为 8),这意味着所有样式都组合在一个 stylesxyz.js 文件中,该文件在正文末尾添加了一个脚本标记,以及其他 js脚本

【讨论】:

  • 我犯了这么愚蠢的错误 :O 谢谢指出,我想已经有一年了,直到今天我才发现,我想知道为什么浏览器从来没有显示过错误
  • 浏览器不会显示格式错误的 html 的错误,他们只是尝试修复它
【解决方案2】:

问题是您指向 css 的链接出现在基本 href 标记之前。

应该是:

<base href="/">
<link rel="stylesheet" href="styles.d42b9ef58619804546db.css">

用于通过浏览器进行正确的 css 处理。

【讨论】:

  • 我在 angular.json 中链接了这样的样式:"styles": ["src/styles.css" [...]],有没有办法让它在这里保持链接但将它移到 index.html 中? (因为 Angular 会自动为我添加它,如果可能的话,我更愿意保持这种状态)
  • 这真的很奇怪,我想,你手动放的。我以前从未见过这种情况。你能提供整个 angular.json 吗?
  • github.com/lori2001/NebuloniaWebsite 这是完整的 repo,你能看一下吗?呵呵:D
猜你喜欢
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
  • 2020-11-26
  • 2015-06-23
  • 1970-01-01
  • 2019-01-16
  • 2021-03-14
  • 2020-03-08
相关资源
最近更新 更多