Webpack, TypeScript, and modules are set to "esnext," resulting in a change to undefined

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.

Answer №1

this in the context of an ESM module is defined as undefined according to the specification (link). Therefore, Webpack is adhering to what the specification dictates.

If you require a similar behavior to accessing the value of this in a non-module script, you can utilize the recently introduced globalThis (spec | MDN).

As mentioned in your question and comments:

I would like to access all the files' exports like this usually does in commonjs

You can achieve this by obtaining the module namespace object from the module itself. For example, within mod.js, you can get the module namespace object as follows:

// *IN* `mod.js` itself
import * as mod from "./mod.js";

The variable mod will hold an object containing properties for all the module's exports (with the default export under the property name default). Here's a complete illustration:

export const a = 42;
export const fn = () => { };

import * as mod from "./mod.js";
console.log(mod.a);        // 42
console.log(typeof mod.fn) // "function"

Alternatively, if you prefer passing around items as a unit, consider explicitly creating an object and exporting it based on your requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm experiencing difficulty in scrolling on my Nextjs web application

Currently, I am facing an issue with my portfolio webpage which is divided into 3 main components - Hero, About, and Portfolio. The layout structure is as follows: export default function RootLayout({ children, }: { children: React.ReactNode }) { ret ...

Error 404: Unable to locate webpack bundle.js

As I dive into learning about Webpack configuration, I keep encountering errors in my console. It appears that my webpack app.bundle.js file is not being found. The page successfully loads with the content of my HTML file displaying, but the app.bundle.js ...

There has been an unhandled runtime error: [object ProgressEvent] occurring with Next.js/Typescript

Exploring the world of nextJS and typescript is new to me. I am currently working on creating a simple blog using nextJS/typescript with a sanity CMS backend. Everything seems to be running smoothly during development, but then I encounter this Unhandled R ...

Required attributes not found for data type in TypeScript

When the following code snippet is executed: @Mutation remove_bought_products(productsToBeRemoved: Array<I.Product>) { const tmpProductsInVendingMachine: Array<I.Product> = Object.values(this.productsInVendingMachine); const reducedPro ...

Issue with linear Graham scan method causing failure when computing convex hull of basic polygon

It is said that the Graham scan algorithm can efficiently find the convex hull of a simple polygon in linear time without requiring the nlogn sorting step since the vertices are already effectively sorted. I have implemented the Graham scan algorithm, and ...

Enhancing a component with injected props by including type definitions in a higher-order component

Implementing a "higher order component" without types can be achieved as shown below: const Themeable = (mapThemeToProps) => { return (WrappedComponent) => { const themedComponent = (props, { theme: appTheme }) => { return <Wrapped ...

Managing file imports in Angular 2+ Unit Testing

Within my project, there are various utility functions that handle data transformations and other tasks. These functions are not contained within a class and are utilized across multiple utility files. Being relatively new to angular testing, I've sp ...

The React component fails to render when clicking on a Material-UI MenuItem

In my code, there is a simple mui Menu, where a MenuItem should trigger the rendering of another React component. The issue I am facing is that the Menu is being rendered in a separate file, which contains the definitions for the close and handleClick func ...

Leveraging an AngularJS service within Angular framework

I am trying to incorporate an AngularJS service into my Angular project. Below is my main.ts file: import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {AppModule} from './app/app.module'; import {UpgradeMo ...

Breaking down types in Typescript: Extracting individual types from an object containing multiple objects

Having a query: const queries = { light: { a... b... }, dark: { a... b... c... d... }, The react element requires a colors parameter that corresponds to one of the themes in the above object, with each theme containing a un ...

An object may be null when its type is A or undefined, but we are certain it is not undefined

Since the release of version 4.8.4, the TypeScript compiler has been flagging an issue with the following code: type A = {v: number} function get_the_first<T>(xs: T[]): T | undefined { if (xs.length > 1) return xs[0]; else ...

Function input custom operator in RxJs

I am currently working on developing a custom rxjs operator. My previous custom operators, such as MonoTypeOperatorFunction or the regular Observable that accepts input like strings or numbers, have been successful. However, I am facing a challenge with cr ...

How can I change an icon and switch themes using onClick in react js?

I have successfully implemented an icon click feature to change the colorscheme of my website (in line 21 and changeTheme). However, I also want the icon to toggle between FaRegMoon and FaRegSun when clicked (switching from FaRegMoon to FaRegSun and vice v ...

Build problems are occurring in the EC2 build box, but they do not arise when building locally

I encountered the following error in my EC2 build environment, but I am unable to reproduce it on my local machine: ERROR in node_modules/rxjs-compat/add/observable/dom/webSocket.d.ts(1,46): error TS2307: Cannot find module 'rxjs/websocket'. In ...

Angular2 authguards encountering issues when trying to run asynchronous functions

I need a way to safeguard my routes by verifying if a user is logged in from the server, but I'm facing issues with asynchronous functions not executing properly. Below is the code snippet that's causing trouble: canActivate (route: ActivatedRo ...

Loop within a promise results in undefined

Within my application, there is a function that returns a promise. Inside this function, I wait for an image in the DOM to become available and then extract that element to generate base64 data from it. getCodesOfOneMerchant(merchantDataEntry: MerchantData ...

What is the benefit of utilizing ngSubmit over just using a basic button and function?

Lately, I've been pondering whether to utilize ngSubmit or simply bind a (click)="submit()" on a button. There's been much debate about using submit and ngSubmit, but is it necessary to rely on the traditional HTML submit method? Particularly wh ...

What could be causing input to be blocked in certain situations while using my Angular directive with compile function?

Recently, I created a directive that adds a class based on a certain condition. You can find the code snippet at the end of this question. The directive functions as expected in a simple use case where it's applied to a required field: <input typ ...

Every time you try to import a config.json file in Typescript, it never fails

I have the most recent version of Visual Studio Code installed. Visual Studio Code is currently utilizing TypeScript v3.3.3. I've successfully installed the following packages via npm, both locally (save-dev) and globally: TestCafe v1.1.0 Core-JS v ...

What is the best way to invoke a method within the onSubmit function in Vuejs?

I am facing an issue with a button used to log in the user via onSubmit function when a form is filled out. I also need to call another method that will retrieve additional data about the user, such as privileges. However, I have been unsuccessful in makin ...