What could be causing my TypeScript code to not be recognized as CommonJS?

I rely on a dependency that is transpiled to ES6.

My goal is to leverage ES2019 features in my own code.

Ultimately, I aim to output ES6.

This is how I set up my tsconfig

{
    "compilerOptions": {
      "module": "CommonJS",
      "removeComments": true,
      "preserveConstEnums": true,
      "sourceMap": true,
      "lib": [
        "es2019",
        "dom"
      ],
      "target":"ES6"
    }
}

Although this setup compiles fine, I encounter a

Uncaught ReferenceError: exports is not defined
error when loading in the browser due to one of my files. To address this, I included
"@babel/plugin-transform-modules-commonjs"
in a .babelrc file:

{
    "plugins": [
        "@babel/plugin-transform-modules-commonjs"
    ]
}

Applying this solution resolves the issue, but I am puzzled as to why it's necessary. My tsconfig already specifies modules as commonjs and the dependency also uses commonjs according to its tsconfig(!?).

Answer №1

For Node applications, the CommonJS module setting is typically used since Node utilizes the commonjs module system. Keep in mind that browsers do not inherently support commonjs modules, hence why you might encounter the exports is not defined error.

If your intention is to output ES6 modules, then make sure to specify

"module": "ES6"

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

The grid expands to cover the entire width of the browser

Hello everyone, I am a newbie when it comes to JavaScript and CSS. I am in need of a code, whether it be JavaScript or CSS, that will allow me to stretch out a grid layout measuring 5 x 2 along with pictures to completely cover the width of the browser wi ...

Input various information into a single form multiple times and automatically submit it to a Google spreadsheet

I have some data that needs to be transferred to an array and then sent to a Google Sheet. The data looks like this: -|PO: 2005 | 12121211212121,| Qty: 45| BIN:110| eBay| 11/6/2017-| PO: 2165 | 333333333,| Qty: 54| BIN:20| google| 11/6/2017- First, I use ...

Guidelines on launching an ionic 4 modal using routes

How can I open a modal using routes? I attempted the following approach, but it did not work as expected: ngOnInit() { this.launchModal(); } async launchModal() { const modal = await this.modalController.create({ component: AuthPasswordR ...

Retrieve values of properties from an array

How can I retrieve property values from an array? const d = [{id: 'Cat'}, {id: 'Dog'}] type ids = ??? //place code here, type should be 'Cat' | 'Dog' (It would also be acceptable if it creates a const enum) ...

Is it possible to determine the specific type of props being passed from a parent element in TypeScript?

Currently, I am working on a mobile app using TypeScript along with React Native. In order to maintain the scroll position of the previous screen, I have created a variable and used useRef() to manage the scroll functionality. I am facing an issue regardi ...

The command 'run-s' is not valid and cannot be found as an internal or external command. Please make sure it is a recognized program or batch file

Unexpectedly, I encountered an issue while attempting to utilize the npm link command to test my local package. Any ideas on how to resolve this? Operating System: Windows 10 Node version: 15.9.0 NPM version: 8.12.2 ...

Is the AngularJS Date property model sending an incorrect value to the server?

There are some puzzling things I am trying to figure out. When using datetimepicker, the Date and time selected appear correctly on the screenshot. The value in the textbox is accurate The model's value in console is correct (but hold on a second... ...

JavaScript can sometimes present peculiar challenges when it comes to setting style attributes, especially when a DOCTYPE is

It seems like I am encountering an issue when trying to dynamically create and modify a <div> element using JavaScript. The problem arises when I use the XHTML 1 Transitional doctype. This is how I am generating the <div>: var newDiv = docume ...

Changing dates in JavaScript / TypeScript can result in inaccurate dates being displayed after adding days

Recently, I encountered an issue with a simple code snippet that seems to produce inconsistent results. Take a look at the function below: addDays(date: Date, days: number): Date { console.log('adding ' + days + ' days'); con ...

CdkVirtualFor does not display any content

I'm facing an issue with implementing cdk-virtual-scroll in my chat application. Unfortunately, it's not showing anything on the screen. Strangely, when I resort to using the regular "ngFor", everything works smoothly. However, as soon as I switc ...

Unable to present information retrieved from REST API, despite data being provided by the server

I'm attempting to make a REST call using a token in the header to retrieve information. To include the required header token, my code is structured as follows within my restClient.js, app.js, and users.js files. //restClient.js import { jsonServerR ...

Preserving variable scope in JavaScript even after defining a function

I am facing an issue with my JavaScript code that involves invoking a function within a function: var obj = { // returns the function with prevent default prepended. run: function(functor, context){ return function(e){ e.preventDefault(); ...

Record the marker's location only once following the completion of its dragging action

Is there a way to make the console log for getPosition only happen when the marker is stopped being dragged, rather than every 0.1 seconds while it's being dragged? Similar to how .getRadius() works - it logs the radius change just once. https://i.ss ...

Creating Typescript libraries with bidirectional peer dependencies: A complete guide

One of my libraries is responsible for handling requests, while the other takes care of logging. Both libraries need configuration input from the client, and they are always used together. The request library makes calls to the logging library in various ...

Exploring intricate designs using HTML and Javascript

After extensive experience with both WPF and HTML5 JavaScript, one thing that stands out to me is the clear organization provided by XAML's defined panels. Grid, StackPanel, DockPanel, WrapPanel, and others offer a straightforward way to achieve consi ...

Pause a YouTube video automatically when the window is not in focus using FancyBox

I have successfully implemented dynamic play/pause functionality for a YouTube video, as demonstrated in my weave. However, I am facing challenges in making it work dynamically with FancyBox using the onBlur event (to pause the video when the window is no ...

Issue with displaying errors in vee-validate when using Vue.js Axios (More details provided)

When working on my Vue project, I encountered an issue while using Vee-Validate and Axios. During an API call to register a user, if the email is already in use, an error is thrown. To handle this error and display the error message, I used the following ...

What is the best way to ensure that an ASync function only continues once all necessary information has been collected?

retrieveStudentGrades() { let grades = {}; let totalStudents = this.state.studentDetails.length; let studentCount = 0; this.state.courses.map((course) => { this.state.studentDetails.map((student) => { request.get( ...

Scrolling Container Following Down the Page, Halts at Its Own Bottom (Similar to Twitter)

I am facing an issue and need some help. I am working on creating a three-column page layout where the middle section is for posts, the right section is for links and references (a bit long), and the left section is fixed. My question is: How can I preven ...

State change shows the previous and current values simultaneously

I've been working on updating the values of initUsers on the DOM. The initial state values work fine, but when I try to update initUsers, it displays different values than expected. Essentially, entriesNum receives a number as an event and changes th ...