0

I'm working on building a test webpack plugin. I have the following code:

module.exports = class TestPlugin{
    constructor(options){
        this.options = options;    
    }

    apply(compiler){
        compiler.plugin("emit", function(){
            console.log(this.options);
        })
    }
}

in my webpack.config.js file I have the following:

const TestPlugin = require('./plugins/TestPlugin');
...  
plugins: [
            new TestPlugin({
                testOption:'testing option'
            }),
...

The issue is that it's printing "undefined" instead of the option object. I put a console.log in the constructor and I get the proper result:

{testOption:'testing option'}

but I can't seem to access it in the apply method, and it returns undefined. What am I doing wrong that I can't access this content? I tried changing "emit" to other things like "done" and I still get the same result.

David Torrey
  • 1,335
  • 3
  • 20
  • 43

1 Answers1

0

I found the answer, the scope was wrong. I was trying to access options through "this" inside an internal function changing the scope of "this". moving it outside of the compiler.plugin function fixed it.

Conversely, changing the

function(){ ... }

to

() => { ... } 

also fixes the issue

David Torrey
  • 1,335
  • 3
  • 20
  • 43