In my setup, I am using webpack with typescript (via ts-loader).
To enable code splitting in webpack, it is necessary to adjust the module setting to esnext in the tsconfig file:
// tsconfig.json
{
"compilerOptions": {
"module": "esnext"
// other configuration ...
}
}
I am facing an issue where I want to pass this
as a parameter in one of my files. While this works fine in node.js using individually compiled files with the native typescript compiler, the problem arises when working with webpack:
in webpack, this
gets replaced with undefined
To simplify, consider the following setup:
Typescript source code snippet:
export var this2 = this;
Output after running tsc
:
export var this2 = this;
Webpack output:
/*!**********************!*\
!*** ./src/index.ts ***!
\**********************/
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "this2": () => (/* binding */ this2)
/* harmony export */ });
var this2 = undefined;
/******/ })()
;
This behavior persists even with multiple other exports in the file, indicating that it's not simply due to an empty context.
The issue seems specific to the combination of webpack and typescript. This behavior does not occur with the same setup using plain javascript instead of typescript or when compiling typescript to javascript for nodejs using tsc
.
It raises questions about the root cause and whether this behavior is intentional.
I'm looking to have a file that registers all its exports without needing to be imported elsewhere. However, the current behavior makes it challenging to access and pass the exports to another function.
Here's a minimal reproduction setup:
Explore this live stackblitz example
Execute webpack
or tsc
in the terminal to observe the outputs in the /webpack
and /tsc
directories.