Last active
March 10, 2018 18:41
-
-
Save bebraw/c3351bec5df053489cf71aa30675c2d5 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
html-webpack-plugin-lite | |
Usage: | |
new HtmlWebpackPluginLite({ | |
title: "Webpack demo", // Available in context | |
template: ({ css, js, title }) => ... html ... | |
}), | |
*/ | |
const path = require("path"); | |
const { RawSource } = require("webpack-sources"); | |
module.exports = class HtmlWebpackPluginLite { | |
constructor(options) { | |
this.options = options; | |
} | |
apply(compiler) { | |
const { template, ...context } = this.options; | |
compiler.plugin("emit", (compilation, cb) => { | |
const files = getFiles(compilation.entrypoints); | |
compilation.assets[`index.html`] = new RawSource( | |
(template || defaultTemplate)({ ...context, ...files }) | |
); | |
cb(); | |
}); | |
} | |
}; | |
function getFiles(entrypoints) { | |
const ret = {}; | |
entrypoints.forEach(entry => { | |
entry.getFiles().forEach(file => { | |
const extension = path.extname(file).replace(/\./, ""); | |
if (!ret[extension]) { | |
ret[extension] = []; | |
} | |
ret[extension].push(file); | |
}); | |
}); | |
return ret; | |
} | |
function defaultTemplate({ css, js, title }) { | |
return `<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>${title}</title> | |
${generateCSSReferences(css)} | |
</head> | |
<body> | |
${generateJSReferences(js)} | |
</body> | |
</html>`; | |
} | |
function generateCSSReferences(files = []) { | |
return files.map(file => `<link href="/${file}" rel="stylesheet">`); | |
} | |
function generateJSReferences(files = []) { | |
return files.map( | |
file => `<script type="text/javascript" src="/${file}"></script>` | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Published to npm. See https://github.com/bebraw/mini-html-webpack-plugin .