Angular 2 \ 4 asset path files not found after prod build

I have an Angular app and I have placed the image and custom font under the 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:

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 also use lazy loadable modules. Everything works as expected in development mode (when I start the ng service). However, when I release prod build (ng build -prod) a dist folder is created with all the js \ css files. If I move these files in the server virtual directory, the images and fonts stored in the assets point to the server root, not a pointer to the virtual directory. For example, I have a project located in myserver.com/myproject/index.html

, whereas this application is looking for images in myserver.com/assets/bg.jpg

instead of myserver.com/myproject/assets/bg.jpg

. Same problem with custom font too. Any idea if any of you ran into this problem? If so, please kindly let me know how to fix this.

Previously, even the generated js \ css files were referenced from the root directory, not from the 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

      

+3


source to share


1 answer


You need to change all paths so that they refer to ./

either ../

their new url. /

c /assets

will always refer to the root of the domain.

For example:



src: url("./assets/fonts/segoeuib.ttf");

or
src: url("../../assets/fonts/segoeuib.ttf");

You can also dynamically set the baseHref via angular-cli (if you are using it) as I explain in here.

+4


source







All Articles