Search code examples
ember.jshandlebars.js

How can a variable be used to set the src of an image in a production Ember app?


I have some images in my Ember app that are static files declared in ember-cli-build.js.

When the app is used in production, the URLs of the images will change from /icons/icon.png to something like /icons/icon-9ace8daf640d474c5472a54df98a4299.png. So this:

<img src="/icons/icon.png">

becomes:

<img src="/icons/icon-9ace8daf640d474c5472a54df98a4299.png">

How don't know why this happens (browser cache?). This breaks my images where the src comes from a variable. For example:

<img src="{{imgURL}}">

If imgURL equals /icons/icon.png, then the browser will be dealing with <img src="/icons/icon.png"> and the request will fail because the URL leads to nothing. In development everything works as expected.

How can a variable be used to set the src of an image in a production Ember app?


Solution

  • This happens because of broccoli-asset-rev, which is used in ember-cli by default.

    First, usually its not a good idea to have a static URL to an image in the .js file at all. It's mostly a better solution to keep it in the template.

    However, to answer your question, you have multiple possible solution.

    1. Don't use broccoli-asset-rev at all. For this just remove it from your package.json, and the files won't get renamed anymore.
    2. Add the images you want to use from .js to the exclude array.
    3. Use the generated assetMap.json to get the new file name.

    To make your best decision you need to understand why broccoli-asset-rev is useful.

    The idea is basically that you can cache your files except your index.html forever on the client and/or proxies, and just use a unique URL for each version. However if your server does not sent the Expires header at all, there is no benefit in using broccoli-asset-rev.