6

I have migrated my webpack from 3.8.1 to 4.41.2. I have been facing the issue of "this" context in standalone javascript file. Please check below code:

util.js

export const calculateSum = (a,b) => {
    this.sum = 0;
    this.sum += a + b;
    return this.sum;
};

Please note that above is sample code depicting the issue.

While using webpack 3.8.1 I was able to use "this" object as used in above example but after migrating to 4.41.2, I am not able to do so.

I have many such cases in very large code base, so it is not feasible to change the code everywhere. Could not find such option in webpack config.

How can I fix in the new version of webpack?

Hriday Modi
  • 2,001
  • 15
  • 22
  • “I am not able to do so” – please describe more clearly what this means: are there any error messages? What is the expected behavior? What is the observed behavior? – Patrick Hund Dec 24 '19 at 14:11
  • @PatrickHund While using webpack 3.8.1 each file had it's own context which was available in `this`, which was nothing but plain javascript object. After upgrading it to 4.41.2 `this` context is not available and now value of `this` is undefined, hence in the code wherever i have used something like `this.something` is breaking because value of `this` is now undefined. I hope this clears your question, let me know if you have any other doubt. – Hriday Modi Dec 25 '19 at 07:32
  • 1
    @HridayModi Create a little git repo which reproduces the issue and I will take a look. – Legends Dec 29 '19 at 11:31
  • How looks webpack result of this function? – felixmosh Dec 30 '19 at 13:56

2 Answers2

2

According to this issue , Webpack turns "this" to undefined in class definitions.

The dev said they fixed the this issue in Webpack 4, maybe you use global webpack installation

If the webpack installation doesn't work, you can try this question, it might be the Babel problem.

Babel 6, Babel 7 has different solution, you can try the config based on your Babel version.

Hope this helps.

fangzhzh
  • 2,172
  • 21
  • 25
0

Try: output: { globalObject: 'this' }

Diego B
  • 1,256
  • 11
  • 19