Skip to content

Instantly share code, notes, and snippets.

@raido
Last active September 18, 2018 14:08
Show Gist options
  • Save raido/93701778cb30571558eddd17e1d1d001 to your computer and use it in GitHub Desktop.
Save raido/93701778cb30571558eddd17e1d1d001 to your computer and use it in GitHub Desktop.
Ember.js simplest asset map bundled with app/ tree - no extra downloads
import Helper from '@ember/component/helper';
import { inject as service } from '@ember/service';
export default Helper.extend({
assetMap: service(),
compute(params) {
const [path] = params;
return this.assetMap.resolve(path);
}
});
const writeFile = require('broccoli-file-creator');
const MergeTrees = require('broccoli-merge-trees');
const path = require('path');
const glob = require('glob');
treeForApp(tree) {
const filesList = glob
.sync(path.join(this.project.root, 'public/**/*'), { nodir: true })
.map((filePath) => {
return filePath.split('public').pop();
}).reduce((obj, currentPath) => {
const file = path.parse(currentPath);
obj[path.join(file.dir, file.name)] = currentPath;
return obj;
}, {});
// Final output:
// export default { '/assets/some-path/my-image': '/assets/some-path/my-image.jpg' }
// Which gets asset-rev rewrite to
// export default { '/assets/some-path/my-image': '/assets/some-path/my-image-<hash>.jpg' }
return new MergeTrees([tree, writeFile('assetsMap.js', 'export default ' + JSON.stringify(filesList))]);
}
import Service from '@ember/service';
import { getOwner } from '@ember/application';
import { computed, get } from '@ember/object';
import { assert } from '@ember/debug';
export default Service.extend({
_assetMap: computed(function() {
return getOwner(this).factoryFor('assetsMap:main').class;
}).readOnly(),
resolve(path) {
const lastDotIndex = path.lastIndexOf('.');
assert('asset-map path must end with extension', lastDotIndex > -1); // just to keep usage consistent for better dev experience
const pathWithoutExtension = path.substring(0, path.lastIndexOf('.'));
return get(this._assetMap, pathWithoutExtension);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment