使用 Angular CLI 并且无法在 CSS 文件中使用相对图像路径 [英] Using Angular CLI and unable to use relative image paths in CSS files

查看:26
本文介绍了使用 Angular CLI 并且无法在 CSS 文件中使用相对图像路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经使用 angular CLI 设置了一个 angular 应用程序,并在 components 目录中创建了一个具有图像的组件.

Have setup an angular app using the angular CLI and have created a component that has an image in the components directory.

例如:

app/
---/common-components
------/header
---------/header.component.ts
---------/header.component.css
---------/images
--------------/image.png

在 CSS 文件中,我使用以下样式:

Within the CSS file I am using the following style:

.image {
    background-url: url('images/image.png');
}

当我运行应用程序时,它给了我一个 304 Not Modified 并且图像没有在预览中显示.如果我使用绝对路径 '/src/app/common-components/header/images' 文件正确加载.但是,这并不理想,因为我希望该组件能够自给自足.

When I run the application it gives me a 304 Not Modified and the image does not show up int he preview. If I use an absolute path '/src/app/common-components/header/images' the file loads properly. However, this is not ideal since I would like the component to be self sufficient.

给出的响应是:

Request URL:http://localhost:4201/images/test-image.jpeg
Request Method:GET
Status Code:304 Not Modified
Remote Address:127.0.0.1:4201

带有空白预览

推荐答案

所有静态资源文件/目录都需要在 angular-cli.json 文件中列出.

All static asset files/directories need to be listed in the angular-cli.json file.

要添加您的资产,您可以:

To add your assets you can either:

  • 将您的图像文件放在默认的 assets 文件夹中(该文件夹已在 angular-cli.json 文件中列出.
  • 或者在 app/ 中添加一个新目录(例如,在您的情况下,您可以使用 app/images,然后在 angular-cli 中引用它.json)
  • Put your image file in the default assets folder (which is already listed in the angular-cli.json file.
  • Or add a new directory inside of app/ (e.g. in your case you could use app/images, and then reference that in angular-cli.json)

angular-cli.json:

angular-cli.json:

{
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico",
        "images"
      ]
    }
  ]
}

引用文件

像评论中提到的@jali-ai background-url 应该是 background-image 并且你可以像这样引用你的资产:

Referencing files

Like @jali-ai mentioned in the comments background-url should be background-image and you can refer to your asset like this:

.image {
   background-image: url('images/image.png'); 
}

以下是 angular-cli 的示例.json 文件引用资产

这篇关于使用 Angular CLI 并且无法在 CSS 文件中使用相对图像路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆