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?
You can use webpack-inject-plugin to inject any JS code as string into the resulting . js bundle created by webpack. This way you can read the File you want to inject as a string (e.g. fs. readFile in nodejs) and inject it with the plugin.
context. You can create your own context with the require. context() function. It allows you to pass in a directory to search, a flag indicating whether subdirectories should be searched too, and a regular expression to match files against. Webpack parses for require.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With