Skip to content

Instantly share code, notes, and snippets.

@thatismatt
Last active August 10, 2020 19:39
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thatismatt/519d11b2c902791bb74b to your computer and use it in GitHub Desktop.
Save thatismatt/519d11b2c902791bb74b to your computer and use it in GitHub Desktop.
Webpack Plugin Question
var path = require("path");
function BlahPlugin (options) { this.options = options; }
function green(str) {
return "\u001b[1m\u001b[32m" + str + "\u001b[39m\u001b[22m";
}
BlahPlugin.prototype.apply = function (compiler) {
var result = "out.txt";
// This is the file that I'd like to "watch"
var template = this.options.template;
compiler.plugin("emit", function (compilation, callback) {
// Adding this line causes a "rebuild" when the template file changes.
// *But* there is no output from the `webpack` command because the hash doesn't change...
compilation.fileDependencies.push(path.join(compiler.context, template));
// ... so indicate that a rebuild has occurred by writing to stdout, this is a bit of a hack!
process.stdout.write(green("BLAH") + " Rebuilding " + result + "\n");
var body = Object.keys(compilation.assets).join("\n");
require("fs").readFile(template, "utf8", function (err, data) {
var content = data.replace("{{body}}", body);
compilation.assets[result] = {
source: function () { return content; },
size: function () { return content.length; }
};
callback();
});
});
};
module.exports = BlahPlugin;
exports.main = "main";
{
"name": "webpack-question",
"version": "0.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
exports.test = "test";
My Template
{{body}}
Footer
var BlahPlugin = require('./blah-plugin');
module.exports = {
context: __dirname,
entry: {
main: "./main",
test: "./test"
},
output: {
path: __dirname + "/dist",
filename: "[name].[hash].js"
},
module: {},
plugins: [
new BlahPlugin({
template: "./tmpl.txt"
})
]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment