Last active
September 18, 2018 14:08
-
-
Save raido/93701778cb30571558eddd17e1d1d001 to your computer and use it in GitHub Desktop.
Ember.js simplest asset map bundled with app/ tree - no extra downloads
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))]); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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