Search code examples
angularsassangular-cli

Angular: Using base-href in combination with scss urls


I'm trying to deploy my Angular app to a server with a subdomain: website.com/magazine/. So to this I'm running the angular-cli command

ng build --prod --base-href=/magazine/

My images are in src/assets/images folder. When I do this:

background-image:url('./assets/images/.....')

the images I refer to via background-image in scss are not showing up because he's trying to fetch the images from website.com/assets/...., ignoring the subdomain.

When I do this (say in sr/app/components/component/component.scss):

background-image: url('../../../assets/images/...')

It works, but the images are stored in the root of the dist folder, which I don't want.

When i do this:

background-image:url('~/assets/images/...');

or this

background-image:url('./assets/images/...');

I get an error

NonErrorEmittedError: (Emitted value instead of an instance of Error)

What I want is that I can refer to the images and keep my relative images path in tact. How do I accomplish this?

I'm using Angular 11 and angular cli 11.1.4


Solution

  • Unfortunately the angular team itself is not really helpful https://github.com/angular/angular-cli/issues/18043 regarding this issue. Which is mind-boggling given how standard this use case it...

    I am using Angular 11. I am using the filter rule but it of course works with bacground-url or any other css rule which uses a url('') path value.

    You can inline the style as mentioned here https://stackoverflow.com/a/66974900/7485690, it will get saved only into the correct folder /assets/filter and it works with --base-href

      <div class="log-wrap" style="filter: url('./assets/filter/round-clip-path.svg#goo');">
    

    Your solution with the relative path works as well but it copies the file into the root folder, so now you have one located in /assets/filter and one in root /.

    .log-wrap {
      filter: url("../../../assets/filter/round-clip-path.svg#goo");
    }
    

    There is one more solution which works the same way but is easier to write:

    .log-wrap {
      filter: url("src/assets/filter/round-clip-path.svg#goo");
    }
    

    Don't forget to disable cache in developer console when experimenting with deployment.