Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative Path for static files like images/css/js etc

I have folder structure of /src/app/some-module/some-component and src/public/images/user.png. Now, when I am wiling to show an image in my some-component I have to give the path as ../../../public/images/user.png which seems to be too naive and wasteful effort once the number of images increase.

Do we have a routing mechanism or relative path in place in angular2 to serve static files. I am using the Angular2 with webpack.

like image 965
Sumit Agarwal Avatar asked Sep 30 '16 12:09

Sumit Agarwal


People also ask

What is the relative path of file style CSS?

Answer. A relative path is an address that points to the current directory or project folder. In the example illustrated in this lesson, the relative path is images/mountains. jpg and it assumes we have an images subfolder nested within a project folder.

Is CSS a static file?

Static files, such as HTML, CSS, images, and JavaScript, are assets an ASP.NET Core app serves directly to clients by default.

What is relative path in JS?

A link that has an absolute path will tell the computer which server to go to and then all the folders that you have to drill down through to get to the target. A link that has a relative path will be written to tell the computer how to get from the folder with the currently viewed topic to the target.


2 Answers

It depends on how your base href looks like.

For e.g if you have

<base href="/src/">

you may easily use below irrespective of where your component template is.

<img src="public/images/user.png" />

Hope this helps!!

like image 158
Madhu Ranjan Avatar answered Oct 03 '22 06:10

Madhu Ranjan


If you use WebPack, it takes care of the paths during the build. The <img src="..."> needs to point to the physical location of the file within the project, relative to the template where it is used.

For instance, in my case, without WebPack, it would be

<img src="img/rhamt-square-248.png" width="172">

since the img/ is directly under the app root.

Whereas with WebPack, this works:

<img src="../../../img/rhamt-square-248.png" width="172">

Otherwise you'd get a compilation error such like:

ERROR in ./src/app/misc/about.component.html
Module not found: Error: Can't resolve './img/rhamt-square-248.png' in '/home/ondra/work/Migration/windup-web/ui/src/main/webapp/src/app/misc'
@ ./src/app/misc/about.component.html 1:402-439
@ ./src/app/misc/about.component.ts
@ ./src/app/app.module.ts
@ ./src/main.ts

like image 34
Ondra Žižka Avatar answered Oct 03 '22 04:10

Ondra Žižka