使用Angular CLI且无法使用CSS文件中的相对图像路径 [英] Using Angular CLI and unable to use relative image paths in CSS files
问题描述
已经使用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未修改,并且预览时图像也不会显示.如果我使用绝对路径"/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.
要添加资产,您可以:
- 将图像文件放入默认的
assets
文件夹(该文件夹已在angular-cli.json
文件中列出.) - 或在
app/
内添加新目录(例如,您可以使用app/images
,然后在angular-cli.json
中引用该目录)
- Put your image file in the default
assets
folder (which is already listed in theangular-cli.json
file. - Or add a new directory inside of
app/
(e.g. in your case you could useapp/images
, and then reference that inangular-cli.json
)
angular-cli.json:
angular-cli.json:
{
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico",
"images"
]
}
]
}
参考文件
注释background-url
中提到的@ jali-ai应该为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屋!