Newer
Older
const fs = require("fs");
const browserify = require("browserify");
.pipe(fs.createWriteStream(`${curDir}/public/main.js`));
function getPageHtml(pageName, pageMeta) {
let html = fs.readFileSync(`${curDir}/public/index.html`, "utf-8");
const setMeta = function (metaName, value) {
return html.replace(
html.match(new RegExp(`<meta.+name="${metaName}".+>`, "g")),
);
};
const setTitle = function (value) {
return html.replace(
html.match(new RegExp(`<title.+</title>`, "g")),
`<title>${value}</title>`
);
};
const setStyleSheet = function () {
return html.replace(
html.match(new RegExp(`<link.+/style.css>`, "g")),
`<link href="/style/style.css" rel="stylesheet" />`
);
};
const setJs = function () {
return html.replace(
html.match(new RegExp(`<script.+main.js.+</script>`, "g")),
`<script type="text/javascript" src="./${pageName}.js"></script>`
);
};
const setAdditionalMeta = function (metas) {
return html.replace(
"</head>",
`${metas
.map(kv => {
const [name, content] = kv;
return `<meta name="${name}" content="${content}"/>`;
})
.join("\n")}</head>`
);
};
html = setMeta("description", pageMeta.description);
html = setTitle(pageMeta.title);
html = setStyleSheet();
html = setJs();
html = setAdditionalMeta(
Object.entries(pageMeta).filter(kv => kv[0] !== "description" && kv[0] !== "title")
);
const pages = fs.readdirSync(`${curDir}/src/pages`);
for (const p of pages) {
const fPath = `${curDir}/src/pages/${p}`;
const targetDirPath = `${curDir}/public/${p}`;
if (!fs.existsSync(targetDirPath)) {
fs.mkdirSync(targetDirPath);
}
const b = browserify();
b.add(fPath)
.bundle()
.pipe(fs.createWriteStream(`${targetDirPath}/${p}.js`));
const page = fs.createWriteStream(`${targetDirPath}/index.html`);
const pageMeta = JSON.parse(fs.readFileSync(`${fPath}/meta.json`, "utf-8"));
page.write(getPageHtml(p, pageMeta));
}
// If pages have been deleted in source, remove them in output directory too.
for (const dir of fs.readdirSync(`${curDir}/public`).filter(f => {
if (build_conf.protected_dirs.includes(f)) return false;
const stats = fs.statSync(`${curDir}/public/${f}`);
return stats.isDirectory();
})) {
if (!pages.includes(dir)) {
const dPath = `${curDir}/public/${dir}`;
try {
const nestedFiles = fs.readdirSync(dPath);
for (const nf of nestedFiles) {
fs.unlinkSync(`${dPath}/${nf}`);
}
fs.rmdirSync(dPath);
} catch (error) {
console.error(error);
}
}