Using the esnext compiler option in Typescript causes issues with importing ES6 modules from external libraries

When I specify either the module or target property in the compiler options to esnext (so I can use import("example") statements), my es6 import statements for npm installed libraries stop working (local modules like "./test.ts" still work).

For example,

import * as asd from "testmodule";
throws an error saying cannot find module 'testmodule'. However, removing both properties makes it work. Why is this happening and which ES standard should I follow in order to use both import("example") and
import * as asd from "testmodule";
statements?


Below is my complete tsconfig.json:

{
  "compilerOptions": {
    "outDir": "./dist/",
    "module": "esnext",
    "target": "esnext",
    "allowJs": true,
    "sourceMap": true
  }
}

Answer №1

To simplify: If the "module" in your configuration is not set to "commonjs", you must explicitly specify a value of "node" for "moduleResolution" to function correctly. Declaring "commonjs" for "module" does this automatically.

It's important to be clear by always stating the "moduleResolution" when defining the "module".

I strongly advise specifying the output module format explicitly every time.

Furthermore, despite similar names, "target" and "module" are unrelated and distinct concepts. It's crucial not to mix them up.

{
  "compilerOptions": {
    "outDir": "./dist/",
    "module": "esnext",
    "moduleResolution": "node",
    "target": "esnext", // this isn't relevant
    "allowJs": true,
    "sourceMap": true
  }
}

"commonjs" serves as an output module format. ESNext dynamic import(...) statements are transpiled into the output module format just like other module syntax such as ES2015 import and export statements.

When specifying --module esnext, it means TypeScript will not transpile any module syntax. The purpose of --module is to denote the output module format, not the source module format.

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

Turn off the ability to select months in PrimeNG Calendar using Typescript

In my Angular 7 project, I am utilizing PrimeNG Calendar and I am looking to disable the month navigator at the component level based on certain conditions. For example, if the current month is February, I want to disable the month navigator after March. ...

Allowing the property of interface/type to not overlap

Is there a way to consolidate multiple interfaces/types in Typescript by merging them? The resulting interface should have all shared properties as mandatory and all unique properties as optional. Here is an example: interface ShopUser { userId: string ...

What is the best way to implement a third-party library that utilizes an outdated import method in Angular 4.x?

Can anyone guide me on how to include the mathjs library in Angular 4.0 and use it within a component? Here are the steps I've taken so far: yarn add mathjs I believe there should be a method for injecting JS libraries during one of the build lifec ...

Can you explain the concept of BuildOptions in Sequelize?

Despite poring through the sequelize documentation and conducting extensive searches online, I have yet to come across a satisfactory answer: Why is BuildOptions necessary and what impact does it have on the created model? import { Sequelize, Model, Data ...

Utilizing Typescript with Next.js API to limit the NextApiRequest query parameter to only accept string types

Is it possible to restrict the req.query in NextJS NextApiRequest to only accept string types instead of string | string[]? For instance, if someQueryParam is currently of type string | string[], but I need it to be just a string. export default async fun ...

Assign a value using the select component from Material UI

I just finished creating a dropdown menu const [selectedValue, setSelectedValue] = useState(''); const handleSelectionChange = (e: any) => { //setSelectedValue(e) console.log('value', selectedValue) } .... <Fo ...

Having trouble getting TypeScript to install using npm on a Mac?

My goal is to use Typescript as a local dependency by checking it into my devDependencies and using it via an npm script after installing it with 'npm install'. However, when I try this on my machine, I find that Typescript (and webpack-cli as w ...

Problem with timing in token interceptor and authentication guard due to injected service

Currently, I am facing an issue where I need to retrieve URLs for the auth service hosted on AWS by reading a config.json file. In order to accomplish this, I created a config service that reads the config file and added it as a provider in app.module. Eve ...

What is the best way to choose a particular radio button from a group of radio buttons using typescript?

Is there a way to automatically select a specific radio button when an item is chosen from a dropdown menu on the webpage using a TypeScript function that is triggered by the dropdown selection? ...

Unable to attach eventName and callback to addEventListener due to the error message stating 'No overload matches this call'

I am attempting to attach an event listener to the input element stored within a class method. This method takes a props object containing eventName and callback. public setTextFieldInputListener({ eventName, callback }: TextFieldListenerProps): void { ...

What is the recommended approach for returning two different types in a TypeScript function?

My API function currently performs a post request and returns an Observable of ModelAResponse, which is an interface I have defined. I now want to modify this function so that it can return an Observable of either ModelAResponse or ModelBResponse based on ...

Creating TypeScript declarations for standard JavaScript functions and objects so they can be accessed in a TypeScript project

In my TS project, I am currently using Node, Express, and Handlebars along with some client-side JS successfully. I don't have any other client-side frameworks like React or Angular integrated at this time. Recently, I have been thinking about conver ...

The trouble with React Navigation encountered with TypeScript: This Entity Cannot Be Invoked

Currently, I'm facing a typescript issue after upgrading to React Navigation 5. The specific error message reads: There is an issue with calling this expression. The union type '{ <RouteName extends "Stack1Screen1" | "Home&quo ...

Using NodeJS to perform asynchronous tasks with setImmediate while also incorporating private class

Today marks my first time experimenting with setImmediate. I've come to realize that it may not be able to run private class methods. Can someone shed some light on this? Why is that the case? Not Functioning Properly When trying to use a private cl ...

Efficiently Combining Objects with Rxjs

I have a specific object structure that I am working with: const myObject = { info: [ { id: 'F', pronouns: 'hers' }, { id: 'M', pronouns: 'his'} ], items:[ { name: 'John', age: 35, ...

Using React Native with TypeScript to Select the Parent and Child Checkboxes within a FlatList

My objective is to ensure that when a user selects a checkbox for one of the parent items ('Non Veg Biryanis', 'Pizzas', 'Drinks', 'Desserts') in the flatlist, all corresponding child items should also be selected au ...

Determining the return type of a function by analyzing its argument(s)

I'm interested in defining a method within a class that will have its type based on the argument provided in the constructor. For example: class A { private model: any; constructor(model: any) { this.model = model; } getModel( ...

Encountering trouble with Angular material library following upgrade to Angular 6

Upon attempting to compile the application, I encountered the following error: ERROR in src/app/app.module.ts(15,5): error TS2304: Cannot find name 'MatToolbarModule'. src/app/app.module.ts(16,5): error TS2304: Cannot find name 'MatSidenavM ...

Typescript type definitions - understanding inheritance

My typescript interface defines the structure of my database data as follows: interface Foo { bar: { fish: { _id: string, name: string, }[], }, starwars: string[], } I want to be able to reference specific parts of this inter ...

String Compression - Number of Elements

Suppose I define a specific type: type SomeType = 'a' | 'b' | 'c' Is there a TypeScript function available that can calculate the number of unique values a variable of type SomeType can hold? assertEq(countUniqueValues(SomeTy ...