Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Dependency in Webpack Plugin

Is it possible to add a dependency from within a Webpack plugin? I'm generating files that use templates, when these templates change I'd like webpack --watch to trigger another build.

Here is the plugin:

function BlahPlugin (options) { this.options = options; }

BlahPlugin.prototype.apply = function (compiler) {

  // This is the file that I'd like to "watch"
  var template = this.options.template;

  compiler.plugin('emit', function (compilation, callback) {
    var body = Object.keys(compilation.assets).join("\n");
    require("fs").readFile(template, "utf8", function (err, data) {
      var content = data.replace("{{body}}", body);
      compilation.assets["out.txt"] = {
        source: function () { return content; },
        size:   function () { return content.length; }
      };
      callback();
    });
  });
};

module.exports = BlahPlugin;

This is taken from this full working project: https://gist.github.com/thatismatt/519d11b2c902791bb74b

If you run ./node_modules/.bin/webpack --watch and modify a js file the compilation automatically triggers and produces the compiled js files and out.txt (as specified in the BlahPlugin). But if you change the tmpl.txt file, that is specified in the webpack config and used in the BlahPlugin then the compilation doesn't re-trigger. (Which is to be expected). But this is what I want to happen, how can I tell Webpack to "watch" that file?

like image 515
thatismatt Avatar asked Feb 26 '16 16:02

thatismatt


People also ask

How do I add a plugin to webpack?

Configuration. const HtmlWebpackPlugin = require('html-webpack-plugin'); const webpack = require('webpack'); //to access built-in plugins const path = require('path'); module. exports = { entry: './path/to/my/entry/file. js', output: { filename: 'my-first-webpack.

Which command is used to create a dependency file in webpack?

context() in the code while building. The syntax is as follows: require. context( directory, (useSubdirectories = true), (regExp = /^\.

Is webpack a dependency?

Any time one file depends on another, webpack treats this as a dependency. This allows webpack to take non-code assets, such as images or web fonts, and also provide them as dependencies for your application.

Does webpack include node_modules?

webpack does not include node_modules dependency!!


1 Answers

I fixed this by adding the following:

compiler.plugin("emit", function (compilation, callback) {
  compilation.fileDependencies.push(path.join(compiler.context, template));
  // ...
});

I've also update the gist, so you can see the full fix there: https://gist.github.com/thatismatt/519d11b2c902791bb74b

NOTE: this works but it is a bit of a hack.

like image 112
thatismatt Avatar answered Oct 06 '22 00:10

thatismatt