Skip to content

Instantly share code, notes, and snippets.

@bebraw
Last active March 10, 2018 18:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bebraw/c3351bec5df053489cf71aa30675c2d5 to your computer and use it in GitHub Desktop.
Save bebraw/c3351bec5df053489cf71aa30675c2d5 to your computer and use it in GitHub Desktop.
/*
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>`
);
}
@bebraw
Copy link
Author

bebraw commented Mar 10, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment