Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
646 views
in Technique[技术] by (71.8m points)

webpack - Using Angular CLI and unable to use relative image paths in CSS files

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

For example:

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

Within the CSS file I am using the following style:

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

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.

The response that is given is:

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

With a blank preview

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Adding assets

To add your assets you can either:

  • 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:

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

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'); 
}

Here is an example of the angular-cli.json file and a reference to an asset


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...