What is the correct way to set up Typescript with external packages for Internet Explorer 11 using Babel 7 and Webpack 4?

After releasing a new version of our react app, we encountered an issue with IE11 complaining about the use of the let keyword. Upon investigation, we discovered that upgrading the query-string package from version 5.1.0 to 6.4.0 introduced the usage of the let keyword in the codebase, which was not being properly compiled from ES6 to ES5 during our build process.

Our project utilizes typescript with babel 7 and webpack 4, which generally works well for our own code and most packages except for query-string.

Below are the configurations we have implemented, and we would appreciate any suggestions on the best way to resolve this issue:

webpack.config:

  {
    test: /\.(t|j)sx?$/,
    exclude: /node_modules/,
    use: [
      { loader: 'babel-loader' },
      {
        loader: 'ts-loader',
        options: { transpileOnly: true }
      }
    ]
  }

tsconfig.json:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "lib": ["webworker", "esnext", "dom"],
    "sourceMap": true,
    "baseUrl": ".",
    "paths": {
      "*": ["./src/*"]
    },
    "jsx": "preserve",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true
  },
  "include": ["./src/**/*", "./**/*.d.ts"],
  "exclude": ["node_modules"]
}

.babelrc

  const presets = [
    '@babel/preset-typescript',
    '@babel/preset-react',
    [
      '@babel/preset-env',
      {
        targets: {
          // React parses on ie 9, so we should too
          ie: 9
        },
        forceAllTransforms: true,
        // Disable polyfill transforms
        useBuiltIns: false,
        // Do not transform modules to CJS
        modules: false
      }
    ]
  ]

Sample Source File

  import queryStringLib from 'query-string'
  queryStringLib.stringify(...)

In an attempt to address the issue, we experimented by removing exlcude node_modules in both webpack.config and tsconfig.json, as well as changing tsconfig.json to target es5. Although this solution worked, it significantly increased CPU load. Thus, it is not an ideal resolution.

Update #1 I just tried, It will work, if I remove exclude node_modules in both webpack.config and tsconfig.json, and change tsconfig.json to target es5. However it will make the computer a lot busier than before. Not a perfect solution.

Thank you, Ron

Answer №1

After some experimentation, I found success by making adjustments to webpack.config:

{
    test: /\.(t|j)sx?$/,
    exclude: /node_modules(?!(\/|\\)query-string)/,
    use: [
      { loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env']
        }
      },
      {
        loader: 'ts-loader',
        options: { transpileOnly: true }
      }
    ]
  }

In simple terms, I made sure to exclude all node_modules except for query-string and included @babel/preset-env as a preset option for babel-loader (which was necessary for proper functionality).

No modifications were needed in the tsconfig.json file.

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

What are the steps to resolve TypeScript errors in OpenLayers version 6.6.1?

Since updating to OpenLayers 6.6.1, I have been bombarded with numerous typescript errors related to generics. For example... import olLayerVector from 'ol/layer/Vector'; import olFeature from 'ol/Feature'; public static highlightOver ...

Is it possible for a property to be null or undefined on class instances?

Consider this TypeScript interface: export interface Person { phone?: number; name?: string; } Does having the question mark next to properties in the interface mean that the name property in instances of classes implementing the interface ca ...

Utilizing Google Sheets as a secure, read-only database for Angular applications without the need to make the sheet accessible to the

Seeking a way to utilize Google Sheets document as a read-only database for my Angular application, I have attempted various methods. However, the challenge with all these approaches is that they necessitate public sharing of the Sheet (accessible to anyon ...

Adding a type declaration to the severity property in React Alert - A guide to Typescript

I've developed a type declaration object for the incoming data, but no matter what I try to define as the type for the property "severity", it's not happy. The options it wants (as displayed below) don't seem feasible. I'm curious if th ...

I'm looking to learn how to implement the delete method in an API using TypeScript. Can anyone help me out

I am seeking guidance on utilizing 'axios' within 'nuxt.js'. I have experimented with sample data, and I am particularly interested in learning how to utilize the 'axios' method within 'nuxt.js' using TypeScript. T ...

What is the method for retrieving the second type of property from an array of objects?

I have a collection of objects that map other objects with unique identifiers (id) and names (name). My goal is to retrieve the name corresponding to a specific id. Here is my initial approach: const obj = { foo: { id: 1, name: 'one' }, ...

Steps for assigning the TAB key functionality within a text area

Is there a way to capture the TAB key press within a text area, allowing for indentation of text when the user uses it? ...

Merging declarations fails to function properly following the release of the npm module

The file core.ts contains the definition of a class called AnyId. In another file named time.ts, more methods are added to the AnyId class. This is achieved by extending the type of AnyId using declaration merging: declare module './core' { in ...

How can you avoid inspecting webpack internal code when debugging in Visual Studio Code with React Typescript or NextJS?

While debugging NextJS Typescript, the Visual Studio Code debugger seems to be stepping into webpack-internal generated source files. The launch.json file in Visual Studio code is configured as: { "version": "0.2.0", "configura ...

Pause and anticipate the occurrence of AdMob's complimentary video reward event within a defined function in Ionic/Typescript

In my ionic app, I have a function that determines if the user has watched a reward video to access another function: let canUseThisFunction = await this.someService.canUseFunction(); if(canUseThisFunction){ console.log("can use"); } else { cons ...

Distribute a TypeScript Project on NPM without exposing the source code

Issue: My library consists of numerous .ts files organized in structured folders. As I prepare to publish this library, I wish to withhold the source (typescript) files. Process: Executing the tsc command results in the creation of a corresponding .js fil ...

How to Reload the Active Tab in Angular 5?

In my project, I have noticed that a listener in one of the tabs causes the entire tab to refresh, resulting in it displaying information from the first tab until I switch to another tab and then go back. 1) Is there a way to refresh only the current tab? ...

Executing the Ionic code within the Xcode Swift environment

I have developed an Ionic application that I successfully compiled in Xcode for iOS. Additionally, I have integrated a widget into the application. My goal is to set it up so that when the application is opened using the regular app icon, it displays the m ...

Download a collection of base64 images as a ZIP file in Angular 4

I am currently developing an Angular2 v4 app using Typescript and I'm looking for a solution to download multiple images (in base64 format) as a Zip file. For instance, I have a sample array like this (containing fake base64 images just for illustrat ...

I'm encountering an error in TestCafe that says "TypeError: Cannot read properties of undefined (reading 'match')". Which specific segment of my code is causing this issue?

retrieveUrlFromEmailData(emailData:any){ const emailContent = emailData.email_text; const urlPattern = /(https?:\/\/[^\n]*)/; const foundUrl = emailContent.match(urlPattern)[0]; return foundUrl } ...

Can you use getters and setters in a TypeScript declaration file?

I am facing an issue with a declaration file for the openUi framework. The framework utilizes a get<propname>() and set<propname>(var) syntax for its properties. In traditional JavaScript, the setup would look like this: sap.ui.getCore().atta ...

Splitting a td tag into multiple columns dynamically with Angular

I am attempting to dynamically split the table element into separate columns. My desired layout should resemble this: The values for name and surname are fixed at 1, but the values for subjects and grades can vary (there may be 2 or more columns). Below ...

Tips on deactivating a div when a checkbox is selected

I am currently working with a checkbox element in my code: <md-checkbox checked.bind="addEventCommand.allDay" change.delegate="allday()">All Day</md-checkbox> When the above checkbox is true, I want to disable the following ...

Declaring Typescript modules across multiple .d.ts files

If my original .d.ts definition file is like this: main.d.ts: declare module myMod { } Now, let's say I want to separate out the security definitions into another file but keep them under the same module. Here's what I'm thinking: main. ...

The issue with Multiselect arises when the array is being set up initially

Using primeng Multiselect, I have implemented a logic to push data based on search value from the backend. To avoid the error of pushing undefined elements, initialization is required before pushing. However, when I initialize the dropdown's array var ...