Angular 2\4 assets path files not found after prod build
You need to change all of the paths so that they are relative ./
or ../
to their new url path. The /
in /assets
will always be relative to root of the domain.
For example:
src: url("./assets/fonts/segoeuib.ttf");
or
src: url("../../assets/fonts/segoeuib.ttf");
You can also set baseHref dynamically through angular-cli (if you're using it) as I explain in my answer here.
Related videos on Youtube
Deepak
Updated on July 09, 2022Comments
-
Deepak almost 2 years
I have an Angular app and I have placed an image and custom font under assets folder(src/assets/images/bg.jpg and src/assets/fonts/segoeui.ttf).
I have referenced bg.jpg and segoeui.ttf in scss file, like so:
styles.css:
@font-face { font-family: "AppFont"; src: url("/assets/fonts/segoeui.ttf"); } @font-face { font-family: "AppFont"; src: url("/assets/fonts/segoeuib.ttf"); font-weight: bold; } html, body { font-family: 'AppFont', Verdana, Geneva, Tahoma, sans-serif; }
login.scss:
#login { background: url("/assets/images/bg.jpg"); background-position: center; background-attachment: fixed; background-size: cover; height: 100vh; }
And I am also using lazy loaded modules. Everything works as expected in development mode(when I run ng serve). However, when I release a prod build (ng build --prod), a dist folder is created with all js\css files. If I move these files in a virtual directory of a server, images and fonts stored in assets are pointing to root of the server, instead of pointing to the virtual directory. For example, I have project located in
myserver.com/myproject/index.html
whereas, this app looks for images inmyserver.com/assets/bg.jpg
, instead ofmyserver.com/myproject/assets/bg.jpg
. Same problem with custom font too. Any idea if any of you have come across this issue? If yes, kindly let me know how to fix this.Earlier, even the built js\css files were referenced from root directory and not from virtual directory. To fix this, I changed index.html from
<base href="/">
to<base href="./">
Version details:
@angular/cli: 1.0.1 node: 6.10.2 os: win32 x64 @angular/common: 4.1.1 @angular/compiler: 4.1.1 @angular/core: 4.1.1 @angular/forms: 4.1.1 @angular/http: 4.1.1 @angular/platform-browser: 4.1.1 @angular/platform-browser-dynamic: 4.1.1 @angular/router: 4.1.1 @angular/cli: 1.0.1 @angular/compiler-cli: 4.1.1
-
Deepak almost 7 yearsThanks Zze, setting baseHref while releasing the build using -bh helped. App now picks up the images\fonts from right place.
-
Gil Epshtain over 5 years@Zze, This solution will work, BUT now I have 2 copies of my assets. #1 in the
dist/assets/
folder. #2. New copy of the same files at the root of the dist:dist/
. I don't need 2 copies, what to do????