angularwebpackwebpack-file-loaderdynamic-url

file-loader does not work with dynamic url in angular


Does file-loader ignore dynamic url?

// app.component.html
<img src="../assets/flower.jpeg" alt="Flower" width="100px">
<img src="{{assets}}flower.jpeg" alt="Flower" width="100px">
// app.component.ts
export class AppComponent {
  assets = '../assets/';
}

As you can see I have 2 images in html. The first image is displayed as expected, but the second one does not work.

The first image is generated and image url in html is also changed, whereas second image url is not hashed.

//eg:
<img src="./assets/b16683a9edb6ebf57d144f8b86cb163e.jpeg" alt="Flower" width="100px">
<img src="../assets/flower.jpeg" alt="Flower" width="100px">

Here is the git repo to reproduce issue, Run npm i && npm start


Solution

  • In your particular case - yes, your path is simply ignored as an incorrect one. However, if your change it to ./{{assets}}flower.jpeg (just for example) you'll get an error

    ERROR in Cannot find module './{{assets}}flower.jpeg'

    Why is that happen? {{assets}} is an Angular binding and the exact value will be known only during the application run not during the building process. So the only way this path can be handled during the building process is just like it is and consequently, file-loaded cannot find any file on this incorrect path and gives you an error.

    I hope I've explained the issue pretty clear. However, feel free to ask more questions in the comments if some details are not clear for you.