Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
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

This comment has been minimized.

Copy link
Owner Author

@bebraw bebraw commented Mar 10, 2018

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