Skip to content

Instantly share code, notes, and snippets.

@lynchbomb
Last active August 30, 2016 21:37
Show Gist options
  • Save lynchbomb/f7622a2f3944f665f30841d6207b44f2 to your computer and use it in GitHub Desktop.
Save lynchbomb/f7622a2f3944f665f30841d6207b44f2 to your computer and use it in GitHub Desktop.
Ember CLI Addon - Critical Inline Style
/**
@module ember-cli
*/
var fs = require('fs-extra');
var path = require('path');
module.exports = {
name: 'ember-cli-inline-style',
project: null,
criticalStylePath: null,
criticalStyleContent: null,
options: null,
/**
Initializes the `tests` and `hinting` properties.
Defaults to `false` unless `ember test` was used or this is *not* a production build.
@public
@method included
@param {Object} app
*/
included: function(app) {
this.options = app.options || {};
},
/**
@public
@method contentFor
@param {String} type
@param {Object} config
*/
contentFor: function(type, config) {
if(type === 'critical-style') {
this.criticalStylePath = this.options.inlineContent[type].path;
this.criticalStyleContent = this.options.inlineContent[type].content;
return '<style>'+ this.criticalStyleContent +'</style>';
}
},
/**
@private
@method postBuild
@param {Object} result
*/
postBuild: function(result) {
var file = null;
var filePath = null;
try {
file = fs.readFileSync(path.join(result.directory, this.criticalStylePath));
} catch (error) {
console.log('ERROR: ' + error);
}
if(file) {
filePath = path.join(result.directory, 'index.html');
this._replacePlaceholder(filePath, file);
}
},
/**
@private
@method _replacePlaceholder
@param {String} filePath
@param {String} file
*/
_replacePlaceholder: function(filePath, file) {
var resolvedFile = fs.readFileSync(filePath, { encoding: 'utf8' });
var re = new RegExp(this.criticalStyleContent, 'g');
fs.outputFileSync(filePath, resolvedFile.replace(re, file));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment