Resolving fingerprinted assets using generateAssetMap

Well, I’ve basically read all the issues on Github and they just say “yeah we need to do it better”, but it hasn’t happened so far. :smile:

I’ve only run into two problems:

  1. The assetMap is on the CDN as well in my case, so it has to be retrieved from there
  2. The initializer was timing out all my tests, so I substituted a “dummy” service that just retuns the passed asset path in dev/testing

This is my version:

import Ember from 'ember';
import ENV from 'volders/config/environment';

export function initialize(container, application) {
  var AssetMap;

  application.deferReadiness();

  if (ENV.APP.CDN_PATH === '') {
    // use an asset map stub in development / testing
    AssetMap = Ember.Object.extend({
      resolve(name) {
        return name;
       }
    });

    container.register('assetMap:main', AssetMap, { singleton: true });
    application.inject('service:assets', 'assetMap', 'assetMap:main');
    application.advanceReadiness();
  } else {
    AssetMap = Ember.Object.extend();

    var promise = new Ember.RSVP.Promise(function(resolve, reject) {
      var assetMapURL = `${ENV.APP.CDN_PATH}assets/assetMap.json`;
      Ember.$.getJSON(assetMapURL, resolve).fail(reject);
    });

    promise.then(function(assetMap) {
      AssetMap.reopen({
        assetMap: assetMap,
        resolve: function(name) {
          // lookup asset in asset map; if not found, try the asset name itself
          return `${assetMap.prepend}${assetMap.assets[name]}` || name;
        }
      });
    }, function() {
      AssetMap.reopen({
        resolve: function(name) {
          return name;
        }
      });
    }).then(function() {
      container.register('assetMap:main', AssetMap, { singleton: true });
      application.inject('service:assets', 'assetMap', 'assetMap:main');
      application.advanceReadiness();
    });
  }
}

export default {
  name: 'asset-map',
  initialize: initialize
};

I set the ENV.APP.CDN_PATH in my config/environment.js by reading a JSON file that I also reuse in the ember-cli-build.js, so I don’t have to change paths in more than location.

edit: actually there was another problem in that the assetMap has a “prepend” entry that has to be prefixed to the actual asset lookup. Maybe this is something that changed recently. I updated my example.