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 is the best way to integrate Next.js with Strapi (or the other way around)?

My goal is to develop an application utilizing Next.js for the frontend, fetching data from a Strapi API hosted on the same server. The plan is to have Strapi handle API and admin routes, while Next.js manages all other routes. I intend to use fetch in Nex ...

Creating variables in Typescript

I'm puzzled by the variable declaration within an Angular component and I'd like to understand why we declare it in the following way: export class AppComponent { serverElements = []; newServerName = ''; newServerContent = &apos ...

Create a custom JavaScript library by incorporating an external library into it as a bundle

As I work on developing a library, one of the dependencies I plan to use is fabricjs. Installing fabricjs involves specific libraries and versions that can be cumbersome for users. Despite successfully installing it in my project and using it, my concern l ...

What is the most efficient approach to handle the next state after calling setState in react with immer?

Using Typescript, React, and Immer, I have set up a state management system to save profiles with multiple options. My goal is to ensure that the active profile has the correct option data before saving it. const { updateProfileList, getProfile } = useProf ...

What is the best way to sort a union based on the existence or non-existence of a specific

My API response comes in the form of a IResponse, which can have different variations based on a URL search parameter. Here is how I plan to utilize it: const data1 = await request<E<"aaa">>('/api/data/1?type=aaa'); const d ...

Step-by-step guide to developing an Angular 2+ component and publishing it on npm

I need assistance with creating an AngularX (2+) component and getting it published on npm. My objective is to publish a modal component I developed in my current Angular App, though currently, I am focusing on creating a <hello-world> component. It ...

Wait until a svelte store value is set to true before fetching data (TypeScript)

I have implemented a pop-up prompt that requests the user's year group. Since I have databases for each year group, I need to trigger a function once the value of userInfo changes to true. My JavaScript skills are limited, and my experience has been ...

Is there a proper way to supply createContext with a default value object that includes functions?

As I was creating my context, I set an initial state and passed the necessary functions for useContext. Although this method is functional, I'm concerned it may present challenges in larger projects. Does anyone have suggestions for a more efficient a ...

Tips for exporting a React Component without using ownProps in a redux setup with TypeScript

I'm currently working on a project using typescript with react-redux. In one of my components, I am not receiving any "OwnProp" from the parent component but instead, I need to access a prop from the redux state. The Parent Component is throwing an er ...

What is the best way to create a jumping animation for an object in Cannon.js and Three.js?

During my quest for a solution, I came across a common practice where users used cannonBody.velocity.y = JUMP_VELOCITY to make an object jump. However, in my scenario, this method only worked while the object was already in motion and not when it was stat ...

Nextjs build: The specified property is not found in the type 'PrismaClient'

I have a NextJS app (TypeScript) using Prisma on Netlify. Recently, I introduced a new model named Trade in the Prisma schema file: generator client { provider = "prisma-client-js" } datasource db { provider = "postgresql" url ...

What is the best way to utilize namespaces across multiple files in your program

I am currently working with TypeScript 1.6.2 and atom-typescript. In my project, I'm attempting to utilize namespaces across separate files: // Main.ts import * as _ from 'lodash' namespace Test { export var value = true } // Another.ts ...

What is the reason behind Angular's repeat filter only being able to access its own element within the return function?

I have successfully implemented some Angular code that is working, however, I am struggling to understand why it works. Coming from a C Sharp background and being new to JS and Typescript. <tr ng-repeat="colleague in Model.FilteredColleagueListModel | ...

Looking to extract the expiration date from an x509 certificate?

I am currently engaged in a project that involves retrieving and displaying certificate information from an Azure integration account using Angular/Typescript. One of the requirements is to show the decoded public certificate to users to extract important ...

The functionality of GetStaticProps with Typescript is only operational when defined as an arrow function, rather than a function

The documentation for GetStaticProps in NextJs explains it as a function declaration. When trying to add types to it, the following code snippet results: export async function getStaticProps(): GetStaticProps { const db = await openDB(); const fa ...

Tips for creating an operation within a JSON document?

Today, I am attempting to customize the appearance of my audiobook list. However, when trying to add an aspectRatio key-value pair to each object in my JSON file, I encountered an error. https://i.stack.imgur.com/Qb3TX.png https://i.stack.imgur.com/qTkmx. ...

angular2: The element 'Validators' is not recognized

When working with Angular2, I encountered an error in Visual Studio Code that is displayed with the following message: enter image description here Here is the content of my tsconfig.json file: { "compilerOptions": { "target": "es5", "module" ...

Saving an array object to a file in JSON formatting

In the midst of my work on an Angular project, I have successfully compiled data into an array and am able to download it as a CSV file using an Angular package. However, I have not been able to locate a suitable package that allows me to download the sa ...

Exploring the traversal of an array of objects within Tree Node

How can I transform my data into a specific Tree Node format? Is there a method (using Typescript or jQuery) to iterate through each object and its nested children, grandchildren, and so on, and modify the structure? Current data format { "content" ...

The useParams() method results in a null value

When attempting to utilize the useParams() hook in nextjs, I am encountering an issue where it returns null despite following the documentation. Here is my current directory structure: pages ├── [gameCode] │ └── index.tsx Within index.tsx ...