Created
August 16, 2019 00:31
-
-
Save gartz/d316af5a98387e1a9b1b2265e188ac49 to your computer and use it in GitHub Desktop.
HtmlWebpackPlugin_templateEngine is a very simple template engine made for HtmlWebpackPlugin, so you can use native js template string to generate the HTML files.
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 optionalCloseTags = ['link', 'meta', 'br']; | |
const serializeAttributes = (attributes) => Object.entries(attributes).map(([key, value]) => { | |
if (typeof value === 'boolean') { | |
return value ? key : ''; | |
} | |
return `${key}="${value}"` | |
}).join(' '); | |
const html = (strList, ...args) => strList.reduce( | |
(acc, cur, idx) => { | |
const value = args[idx - 1]; | |
let strValue; | |
if (Array.isArray(value)) { | |
const matchIndent = acc.match(/\n[ ]*$/g) | |
const suffix = matchIndent ? matchIndent[0] : ''; | |
strValue = value | |
.map(item => html`${item}`) | |
.join(suffix); | |
} else if (typeof value === 'object') { | |
if (value.tagName) { | |
strValue = html`<${value.tagName} ${value.attributes}>` | |
+ (optionalCloseTags.includes(value.tagName) ? '' : `</${value.tagName}>`) | |
} else { | |
const matchTags = acc.match(/<([^>])+/mg); | |
strValue = matchTags[matchTags.length - 1] === acc | |
? serializeAttributes(value) | |
: `${value}`; | |
} | |
} else { | |
strValue = value || '' | |
} | |
return `${acc}${strValue}${cur}`; | |
} | |
); | |
// export default `html` | |
// Demo: | |
// | |
// html` | |
// <!DOCTYPE html> | |
// <html lang="en"> | |
// <head> | |
// ${htmlWebpackPlugin.tags.headTags} | |
// | |
// <title>${htmlWebpackPlugin.options.title}</title> | |
// </head> | |
// | |
// <body> | |
// <div id="app"> | |
// Loading... | |
// </div> | |
// | |
// ${htmlWebpackPlugin.tags.bodyTags} | |
// </body> | |
// </html> | |
// `; | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment