Krishna Chaitanya
Krishna Chaitanya

Reputation: 2663

Angular: Images not loading in production

I have my images in src/assets/images/ directory and in html i am referring to them like below

<img src="assets/images/penndot-logo-full.png" />

This works fine in dev mode. But in prod it give 404 error. I have built my application using the below command

ng build --prod --deploy-url /myapp --base-href /myapp

This section explains that in prod angular will resolve the image paths with what is present in base-href tag. I checked my compiled index.html page and the base-href points to /myapp but still the images are not being resolved.

Upvotes: 2

Views: 5450

Answers (1)

Mahmoud Fawzy
Mahmoud Fawzy

Reputation: 1675

Angular makes use of the base href to tell router how to compose navigation URLs. If your application exists at the root, then you can use / as the href value as shown below.

<base href="/">

If you build the project the Angular project for the production environment using the default values you will get the following index.html generated.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>some title</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>

but as i see your application may exist in sub folder in production mode called myapp

so you need to make your base href like this <base href="/myapp/">

so the missing piece in your command is the ending slash in /myapp/ as you see below this from angular official documentation:

ending slash in base href

besides that you can merge both application base for router & base for assets if they got the same base like /myapp/ so no need to specify deploy-url:

ng build --prod --base-href /myapp/

Upvotes: 3

Related Questions