Webpack is throwing an error with code TS2304 stating that it cannot locate the names 'Map', 'Set', and 'Promise'

I am currently working with the following webpack.config.js file

var path = require("path");
var webpack = require('webpack');

module.exports = {
  entry: {
    'ng2-auto-complete': path.join(__dirname, 'src', 'index.ts')
  },
  resolve: {
    extensions: ['', '.ts', '.js', '.json', '.css', '.html']
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: "[name].umd.js",
    library: ["[name]"],
    libraryTarget: "umd"
  },
  externals: [
    /^rxjs\//,    //.... any other way? rx.umd.min.js does work?
    /^@angular\//
  ],
  devtool: 'source-map',
  module: {
    loaders: [
      { // Support for .ts files.
        test: /\.ts$/,
        loaders: ['ts', 'angular2-template-loader'],
        exclude: [/test/, /node_modules\/(?!(ng2-.+))/]
      }
    ]
  }
};

In addition to that, I have created this tsconfig.json file

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmitHelpers": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "pretty": true,
    "allowUnreachableCode": true,
    "allowUnusedLabels": true,
    "noImplicitAny": false,
    "noImplicitReturns": false,
    "noImplicitUseStrict": false,
    "noFallthroughCasesInSwitch": false,
    "allowSyntheticDefaultImports": true,
    "suppressExcessPropertyErrors": true,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "dist",
    "baseUrl": "src"
  },
  "files": [
    "src/index.ts"
  ],
  "exclude": [
    "node_modules"
  ],
  "compileOnSave": false,
  "buildOnSave": false
}

Upon running the tsc command, everything runs smoothly.

ng2-auto-complete (master)$ tsc --declaration
ng2-auto-complete (master)$ 

However, when executing the webpack command, TypeScript compile errors start showing up.

ng2-auto-complete (master)$ webpack
ts-loader: Using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c38355c313e3f3c45443c493d7d737d7">[email protected]</a> and /Users/allen/github/ng2-auto-complete/tsconfig.json
Hash: bd6c50e4b9732c3ffa9d
Version: webpack 1.13.2
Time: 5041ms
                       Asset     Size  Chunks             Chunk Names
    ng2-auto-complete.umd.js  24.4 kB       0  [emitted]  ng2-auto-complete
ng2-auto-complete.umd.js.map  28.4 kB       0  [emitted]  ng2-auto-complete
    + 11 hidden modules

ERROR in /Users/allen/github/ng2-auto-complete/node_modules/@angular/platform-browser/src/dom/dom_renderer.d.ts
(18,37): error TS2304: Cannot find name 'Map'.

ERROR in /Users/allen/github/ng2-auto-complete/node_modules/@angular/platform-browser/src/dom/dom_adapter.d.ts
(96,42): error TS2304: Cannot find name 'Map'.

ERROR in /Users/allen/github/ng2-auto-complete/node_modules/@angular/platform-browser/src/web_workers/worker/location_providers.d.ts
(21,86): error TS2304: Cannot find name 'Promise'.
...
ng2-auto-complete (master)$ 

If anyone knows how to address the TS2304 errors while using the webpack command, your help would be greatly appreciated.

Note that the node_modules directory has been excluded in the tsconfig.json file like so:

"exclude": [ "node_modules" ],

Also, the type definitions are present in the node_modules directory as evidenced by the devDependencies section below:

  "devDependencies": {
    "@types/core-js": "^0.9.32",
    "@types/node": "^6.0.31"

Additionally, attempts were made using a typings.json file and typings directory without success.

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160815222444"
  }
}

For reference, here are the versions of various tools being used:

$ node --version
v5.7.1
$ npm --version
3.6.0
$ tsc --version
Version 2.0.0

If you have any insights on resolving the TS2304 errors encountered with the webpack command, please do share your expertise. Thank you!

Answer №1

Incorporating this adjustment into my tsconfig.json file has resulted in seamless execution without encountering any errors.

  "compilerOptions": {
    "target": "es5",
    "lib": ["es5", "es6", "dom"],  <--- this
    ...
  }

While unsure if the lib functionality pertains to Typescript 2.0 features, it appears that there are multiple libraries at our disposal.

Based on the typescript config schema (highlighting es2015.collection)

 "lib": {
      "description": "Specify library file to be included in the compilation. Requires TypeScript version 2.0 or later.",
      "type": "array",
      "items": {
        "type": "string",
        "enum": [ "es5", "es6", "es2015", "es7", "es2016", "es2017", "dom", "webworker", "scripthost", "es2015.core", "es2015.collection", "es2015.generator", "es2015.iterable",
                    "es2015.promise", "es2015.proxy", "es2015.reflect", "es2015.symbol", "es2015.symbol.wellknown", "es2016.array.include", "es2017.object", "es2017.sharedmemory" ]
      }
    }

This adjustment has addressed compile-time issues, but a lingering inquiry remains regarding why the tsc command executes error-free whereas webpack does not. Could it be that tsc automatically scans for all possible libraries regardless of the presence of lib declaration in tsconfig.json?

Answer №2

ES6 introduces new features like Map, Set, and Promise. Make sure your tsconfig.json file is configured correctly:

"target": "es5" 

When targeting es5, the compiler uses the standard es5 lib.d.ts, which may not include definitions for these ES6 types.

To access the definitions for these types, switch to using the lib.es6.d.ts:

"target": "es6" 

Answer №3

To enhance your code, simply include the following:

 "lib": ["es6"] // indicating at least ES6 compatibility

Keep the target unchanged. The target is crucial in instructing Typescript on which version of ECMAScript to compile your .ts files. You have the flexibility to modify it if the browser supporting your application will be compatible with that specific ECMAScript version.

As an illustration, I utilize "target": "es5" along with "lib": ["es6"].


One more reason might be:

Your .ts file does not fall under "rootDir": "./YourFolder",

Answer №4

If you're struggling to get any of these solutions to solve your issue, remember that if you explicitly mention the file you want to compile in the command line or package.json, TypeScript compiler (tsc) will ignore your tsconfig.json settings. To make it work, define the "files" and "outDir" in your tsconfig.json and try one of the suggested "lib" solutions. Afterwards, run the compilation with just:

tsc --sourcemaps

Answer №5

Use the following command line option if adding lib is not working in tsconfig.json: tsc index.ts --lib "es6"

If you encounter issues with including lib in tsconfig.json, consider utilizing the above-mentioned command line option.

Answer №6

To resolve the issue, I had to download and install the core-js typings using npm

npm install @types/core-js

clarification:
The purpose of @types npm packages is to acquire type definitions through npm. This functionality is a key aspect of TypeScript 2.0.

@types are intended to supersede existing tools like typings and tsd, although support for these will be maintained for a period.

Answer №7

After finding that the typical solution of adding "es6" to lib did not work for my situation, I realized it was due to a different issue. My problem arose from using an older version of node while having installed a newer version of "@types/node" via npm. To resolve the errors I was encountering when trying to use tsc, I uninstalled the newer node typing and replaced it with a specific version compatible with my installed node version (v9.11.1). This simple adjustment fixed the issue for me.

Answer №8

Visit this link for more information

npm install typings -g
typings install

An important reminder: the command above is deprecated in npm version 5.6.0! Please make sure to use npm install @types/core-js instead.

Answer №9

My current version of node.js is 10.16.3. I encountered an issue where the typescript compiler was not recognizing my tsconfig.json file.

I found three solutions that resolved the problem for me:

  1. Using ts-node to compile and run the file
  2. Adding
    tsc filename.ts --lib "es6", "dom"
    during compilation
  3. Installing @types/node to enable error-free execution with tsc filename.ts

Answer №10

To fix this issue, update the specified settings in your tsconfig.json file.

"lib": [
      "es2018",
      "dom",
      "es5", 
      "es6"
    ],
"module": "es2015",
"target": "es6"

Next, execute the following command in your terminal.

npm install @types/es6-shim

PROBLEM SOLVED!

Answer №11

To update your tsconfig.json file, simply replace the value for "target" from "es5" to "es6"

Answer №12

The solution to this problem is quite simple - just include the map method in your TypeScript file by adding the following code:

import { map } from 'rxjs/operators';

Answer №13

In order to resolve the issue, I found that adding @types/node was the solution:

yarn add @types/node --dev

If you prefer using npm instead:

npm install @types/node --dev

Furthermore, it is recommended to include "es6" in the "lib" array of your tsconfig.json if you plan on utilizing features like "Map", "Set", or "Promise".

Answer №14

If you're working with ES6, consider using the following method:

tsc filename.ts --lib es2015

Answer №15

For my situation, I found the solution by running:

npm install typings -g
typings install

Doing this resolved the issue for me.

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 parameter type 'DateInput' cannot be assigned to the parameter type 'Date'

I am currently utilizing fullcalendar for my project. However, I would like to utilize my local models instead of fullcalendar's model. The issue arises when attempting to create a new instance of my own model, as it displays the following error messa ...

Steps to transfer extra files such as config/config.yaml to the .next directory

I have the following folder structure for my NextJS project: _posts/ components/ hooks/ config/ <--- includes config.yaml file for the server pages/ public/ .env.local ... yarn build successfully copies all dependencies except for the config/ folder. ...

"Unsuccessful API request leads to empty ngFor loop due to ngIf condition not being

I have been struggling to display the fetched data in my Angular 6 project. I have tried using ngIf and ngFor but nothing seems to work. My goal is to show data from movies on the HTML page, but for some reason, the data appears to be empty. Despite tryin ...

What could be the reason for the crash caused by ngModel?

The usage of [(ngModel)] within a *ngFor-Loop is causing an endless loop and crashing the browser. This is how my HTML looks: <div class="container"> <div class="row" *ngFor="let item of controlSystemTargetViewModel.values; let index = i ...

Implementing dynamic loading of script files in app.component.ts using Angular

I am currently working with Angular2 and TypeScript. Within my app.component.ts file, I need to dynamically load script files based on the current navigator language. To achieve this, I have added the following function in my home.component.ts: export cl ...

It only takes half a minute for ts-node-dev to set up its watchers

Having tried both ts-node and ts-node-dev, I am frustrated by the fact that they take almost the same amount of time to start my app server. This issue has been a recurring problem for me, with no successful attempts at resolving it. Currently, I am opera ...

Maximizing the potential of process.hrtime.bigint

Whenever I include the following code: const a = process.hrtime.bigint(); The linter says it's okay, but during compilation, I encounter this error message: error TS2339: Property 'bigint' does not exist on type 'HRTime'. This ...

Using source maps with Typescript in Webpack (source maps not visible while using webpack-dev-server)

I am currently experimenting with Typescript in combination with Webpack, utilizing the 'awesome-typescript-loader' plugin. However, I am encountering an issue where the source maps are not displaying in the browser when running webpack-dev-serve ...

Best practice for implementing FieldValue.serverTimestamp() in a Typescript project

When using Tyepscript, I attempted to set the createdAt field in one of my Firebase functions with FieldValue.serverTimestamp(), but encountered an error message: Cannot read properties of undefined (reading 'serverTimestamp'){"severity&qu ...

UI thread was blocked due to withProgress being invoked from an external library function

Currently enhancing an extension that is almost finished, but facing a challenge in adding visual cues for lengthy operations. Initially suspected a missing async/await in the code, but struggling to identify the cause. The progress indicator isn't di ...

Tips for developing a personalized form validator for validating JSON data exclusively in Angular

Within my Angular application, there exists a reactive form that has a single control known as configJson, which is visually represented by a <textarea> element in the DOM. The primary goal is to validate this specific form control to ensure that it ...

Error: The variable "prisma" is not defined in this context - Next.js version 14

While working with Prisma and next.js 14, I encountered an issue with the Stripe payment API. The error message ReferenceError: prisma is not defined popped up. How can I resolve this? import { NextApiRequest, NextApiResponse } from "next" import ...

How to Avoid Name Conflicts when Importing Modules in Angular 2?

I recently experienced a potential name collision issue, as I inadvertently created a class with the same common name Message that already exists in PrimeNG: import {Message} from "primeng/primeng"; import {Message} from "./dto"; Since it was my own code ...

Enhancing Favicon and Splash Screen Images with Hash Content in Next.js

I'm configuring the PWA favicon like this: <link rel="shortcut icon" href="assets/icons/favicon.ico" /> <link rel="icon" sizes="16x16 32x32 64x64" href="assets/icons/favicon.ico" /> <lin ...

The bamboo construction falters as webpack is unable to locate the node_modules

After setting up my Angular project with webpack in version 1.7, everything runs smoothly locally when I execute the npm run build task to launch webpack. However, I encountered an issue when trying to set up a plan for continuous integration using bamboo ...

Finding the index of a table row based on its ID in TypeScript

Is there a way to retrieve the index of a specific row in a table using its ID without the need for clicking or looping through all rows? Here is an example of my HTML structure: <table id="tabId"> <tr id="a"> <td>ss</td> ...

Update the names of the output fields within the returned object from the API

Recently I delved into nodejs and typescript to create an API using express. I attempted to return a custom object in my API structured as follows: export class Auction { private _currentPrice:number = 0; private _auctionName:string; public ...

Field types: Elements encased within square brackets

When using Flow Types: export type GroupType = { options: OptionsType, [string]: any, }; What does the syntax [string]: any signify? Edit : Appreciate all the responses provided. How should I interpret this particular piece of code? import type { ...

Next.js not storing prop value in state variable

In my current project using Next.js, I am facing an issue with passing props from one component to another. These props include properties of a product such as name, ID, and quantity. This particular component is a Cart Component responsible for rendering ...

On a mobile device, the keyboard is hiding the PrimeNG dropdown

While my dropdown works flawlessly on a desktop browser, I encountered an issue when accessing it on an Android device. The dropdown immediately disappears and the virtual keyboard pops up, which is not the case on iOS devices. I suspect that the problem ...