broccolijs / broccoli-plugin

Base class for Broccoli plugins
MIT License
25 stars 25 forks source link

Example code fails with TypeError: Missing `new` operator #10

Closed gcharnock closed 8 years ago

gcharnock commented 8 years ago

Trying to run the sample plugin against broccoli-plugin-1.2.1 fails with the following error:

/home/gareth2/dev/react-redux-tutorial/node_modules/broccoli-plugin/index.js:5
  if (!(this instanceof Plugin)) throw new TypeError('Missing `new` operator')
                                 ^

TypeError: Missing `new` operator
    at Plugin (/home/gareth2/dev/react-redux-tutorial/node_modules/broccoli-plugin/index.js:5:40)
    at MyPlugin (/home/gareth2/dev/react-redux-tutorial/broccoli-plugins/babel.js:10:10)
    at Object.<anonymous> (/home/gareth2/dev/react-redux-tutorial/Brocfile.js:10:10)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.loadBrocfile (/home/gareth2/dev/react-redux-tutorial/node_modules/broccoli/lib/builder.js:245:14)

My guess is that the if (!(this instanceof Plugin)) throw new TypeError('Missingnewoperator') broke the example when it was added?

(I've attached the sample as it was when I encountered this error below).

var Plugin = require('broccoli-plugin');
var path = require('path');

// Create a subclass MyPlugin derived from Plugin
MyPlugin.prototype = Object.create(Plugin.prototype);
MyPlugin.prototype.constructor = MyPlugin;
function MyPlugin(inputNodes, options) {
  options = options || {};
  Plugin.call(this, inputNodes, {
    annotation: options.annotation
  });
  this.options = options;
}

MyPlugin.prototype.build = function() {
  // Read files from this.inputPaths, and write files to this.outputPath.
  // Silly example:

  // Read 'foo.txt' from the third input node
  var inputBuffer = fs.readFileSync(path.join(this.inputPaths[2], 'foo.txt'));
  var outputBuffer = someCompiler(inputBuffer);
  // Write to 'bar.txt' in this node's output
  fs.writeFileSync(path.join(this.outputPath, 'bar.txt'), outputBuffer);
};
gcharnock commented 8 years ago

The issue was that this error message to todo with how the plugin is eventually called in the client code, not the Plugin.call itself. I was following an outdated tutorial when I realised it was out of date. I hadn't updated the client code.

In your Brocfile change this:

var plugin =  require('my-plugin');

To something like:

var Plugin =  MyPlugin('src');
...
var plugin = new Plugin(tree);

Closing issue. Hopefully this will be a helpful google-crumb for someone else.