eunomia-controller
Version:
84 lines (75 loc) • 3.55 kB
JavaScript
;
var fs = require('fs');
var ejs = require('ejs');
var system = require('./../../variables')('./eunomia.json');
var isMissing = function isMissing(data, message) {
return typeof data === 'undefined';
};
exports.generate = function (writeToPath, distToPath, stats, production) {
return require('./../../task/index')('html', function (resolve, reject) {
if (!fs.existsSync('./eunomia.json')) {
reject("eunomia.json required within the root of the project");
} else {
var eunomia = system;
if (!eunomia.generate.html.enabled) {
resolve();
return false;
}
try {
if (!production) {
// Find the primary chunk used within this project
var bundle = stats.compilation.chunks.find(function (x) {
return x.name === 'main';
}).files[0];
if (bundle == null || typeof bundle === 'undefined' || bundle == '') {
return reject('No main chunk found.');
}
// Get the contents of the html.ejs file to structure the index.html
var fullPath = __dirname + '/html.ejs';
var template = fs.readFileSync('' + fullPath, 'utf8');
if (template == null || typeof template === 'undefined' || template == '') {
return reject('File \'html.ejs\' contains no content.');
}
// Generate the rendering function for the html.ejs file
var render = ejs.compile(template, { filename: '' + fullPath });
if (typeof render !== 'function') {
return reject('Render contains no function.');
}
// Render the output for the index.html from the html.ejs containing certain variables
var output = render({ debug: true, bundle: '' + distToPath + bundle, config: system.generate.html.app });
if (output == null || typeof output === 'undefined' || output == '') {
return reject('Rendered output contains no content.');
}
// Write the new index.html to a file in the public folder
fs.writeFileSync(writeToPath + '/index.html', output, 'utf8');
fs.exists(writeToPath + '/index.html', function (exists) {
if (exists) return resolve();else return reject('\'index.html\' has not been created');
});
} else {
try {
fs.exists('' + system.config.webpack, function (exists) {
if (exists) {
var webpackConfig = require('../../../../' + system.config.webpack);
var _fullPath = __dirname + '/html.ejs';
var assets = JSON.parse(fs.readFileSync('' + writeToPath + distToPath + 'assets.json', 'utf8'));
var _template = fs.readFileSync('' + _fullPath, 'utf8');
var _render = ejs.compile(_template, { filename: '' + _fullPath });
var _output = _render({ debug: webpackConfig.debug, bundle: assets.main.js, config: system.generate.html.app, fonts: typeof system.generate.html.fonts === 'undefined' ? [] : system.generate.html.fonts });
fs.writeFileSync(writeToPath + '/index.html', _output, 'utf8');
resolve();
} else {
reject("Webpack config not found. eunomia.json requires a config.webpack path");
}
});
} catch (e) {
console.log(e);
reject(e);
}
}
} catch (e) {
console.log(e);
reject("Failed to create a index.html");
}
}
});
};