eunomia-controller
Version:
92 lines (74 loc) • 3.36 kB
JavaScript
const fs = require(`fs`);
const ejs = require(`ejs`);
const system = require(`./../../variables`)(`./eunomia.json`);
const isMissing = (data, message) => typeof data === 'undefined'
exports.generate = (writeToPath, distToPath, stats, production) => require(`./../../task/index`)(`html`, (resolve, reject) => {
if (!fs.existsSync(`./eunomia.json`)) {
reject("eunomia.json required within the root of the project")
}
else {
const eunomia = system;
if (!eunomia.generate.html.enabled) {
resolve()
return false
}
try {
if (!production) {
// Find the primary chunk used within this project
const bundle = stats.compilation.chunks.find(x => 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
const fullPath = `${__dirname}/html.ejs`
const 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
const 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
const 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`, (exists) => {
if(exists) return resolve();
else return reject(`'index.html' has not been created`)
});
}
else {
try {
fs.exists(`${system.config.webpack}`, (exists) => {
if (exists) {
const webpackConfig = require(`../../../../${system.config.webpack}`);
const fullPath = `${__dirname}/html.ejs`
const assets = JSON.parse(fs.readFileSync(`${writeToPath}${distToPath}assets.json`, `utf8`));
const template = fs.readFileSync(`${fullPath}`, `utf8`);
const render = ejs.compile(template, { filename: `${fullPath}` });
const 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");
}
}
});