Leveraging es6-promise in conjunction with TypeScript 2.1 and ES5 Webpack for streamlined async/await functionality

Utilizing es6-promise with TypeScript version 2.1.1 that targets ES5 and webpack in my project has presented some challenges.

app.ts

import "es6-promise/auto";

export class Foo {
    bar() : Promise<string>{
        return Promise.resolve("baz");
    }
}

webpack.common.js

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

module.exports = {
    entry: {
        'app': './app.ts',
    },

    output: {
        path: 'dist/ie',
        filename: '[name].js'
    },

    resolve: {
        extensions: ['', '.ts', '.js']
    },

    devtool: 'source-map',

    module: {
        loaders: [
            {
                test: /\.ts$/,
                loaders: ['awesome-typescript-loader']
            },
        ]
    },
    plugins: [  
        new webpack.ProvidePlugin({
            Promise: 'imports?this=>global!exports?global.Promise!es6-promises'
        }),

    ]
};

package.json

{
  "name": "foo",
  "ieArtifactName": "foo",
  "version": "3.0.0-1",
  "description": "...",
  "main": "src/app.ts",
  "author": {
    "name": "...",
    "email": "...",
    "url": "..."
  },
  "dependencies": {
    "@types/es6-promise": "0.0.32",
    "@types/jquery": "^2.0.34",
    "@types/underscore": "^1.7.34",
    "es6-promise": "^4.0.5",
    "es6-promise-promise": "^1.0.0",
    "es6-promises": "^1.0.10",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "^0.6.23"
  },
  "devDependencies": {
    "awesome-typescript-loader": "=2.2.4",
    "clean-webpack-plugin": "^0.1.14",
    "css-loader": "^0.26.0",
    "exports-loader": "^0.6.3",
    "http": "0.0.0",
    "https": "^1.0.0",
    "imports-loader": "^0.6.5",
    "load-grunt-tasks": "^3.5.2",
    "node-static": "^0.7.9",
    "pug": "^2.0.0-beta6",
    "pug-html-loader": "^1.0.9",
    "raw-loader": "^0.5.1",
    "sass-loader": "^4.0.2",
    "style-loader": "^0.13.1",
    "typescript": "^2.1.1",
    "webpack": "^1.13.3",
    "webpack-dev-server": "^1.14.1",
    "webpack-merge": "^0.14.0"
  }
}

My approach to starting webpack involves using the following command line:

webpack --config config/webpack.common.js

The behavior observed is as follows:

  • Webstorm version 2016.3.1 provides proper highlighting for all elements.
  • The compiler successfully runs.
  • The compiler does generate 2 errors

    ERROR in [default] D:...\app.ts:4:16 Cannot find name 'Promise'.

In an attempt to address this issue, I tested various imports such as es6-promise, es6-promises, es6-promise-promise, and different import expressions.

After adding

import {Promise} from "es6-promise"
, Webstorm indicates it as an unused import, yet the error disappears. However, I question whether it's feasible to use Promises targeting ES5 without the need for imports. The concern arises from potential extensive modifications required if the target were to be switched to ES6.

Challenges with async

My objective includes enabling the usage of async/await, a feature I appreciate from C# due to its effectiveness in avoiding callback complexities. Upon modifying the code as shown below:

export class Foo {
    async bar() : Promise<string>{
        return "baz";
    }
}

A new compilation error surfaces

Cannot find name 'Promise'.

Further attempts to rectify by importing

import {Promise} from "es6-promise";
leads to exacerbating the issue.

Duplicate identifier 'Promise'. Compiler reserves name 'Promise' in top level scope of a module containing async functions.

Answer №1

To allow the TypeScript compiler to recognize ES2015 promises, simply include "es2015.promise" in the list of library files within your tsconfig.json:

{
    "compilerOptions": {
        "lib": [
            "dom",
            "es5",
            "scripthost",
            "es2015.promise"
        ]
    }
}

ES2015 introduced native promises which are not available in ES5 - the target environment you're using. This is why the TypeScript compiler may throw an error when it can't find the name Promise. By adding a polyfill, a Promise will be present at runtime. The solution above ensures TypeScript acknowledges this.

Edit Sven-Michael

You don't necessarily need to provide Promise through a plugin. It's enough to do import "es6-promise/auto";

Answer №2

Another option is to incorporate the es6-promise polyfill into your project. Below is an example of how you can include it using Typescript and Webpack2:

entry: {
    'es6-promise',    
    'mainApp': './mainApp.ts',
}

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 approach for replacing numerous maps within an rxjs observable array?

Is there a more efficient way to retrieve only 3 items from an array? If you have any suggestions, I would appreciate it! Thank you. loadAsk!: Observable<any[]>; this.loadAsk.pipe( map(arr => arr.sort(() => Math.random() - .5)), map((item ...

How to Include a JavaScript Library without Export in Angular 2.0.0 using Angular CLI and Webpack

In my Angular 2.0.0 project, I use Angular CLI and Webpack for building. I'm looking to incorporate a JS library (specifically xmltojson.js from https://www.npmjs.com/package/xmltojson) that contains a variable (xmlToJSON) referencing a function. Thi ...

React-snap is unable to locate the specified file or directory

My application operates as follows: Webpack builds client bundles that are output to /client/app/public/build. An express server is launched from /server/index.js and generates a handlebars template using specified environment variables. Upon executing ...

Ensuring robust type safety when using various maps and multiple enums as their keys

I am working on creating a type-safe function for retrieving values from a map. The function needs to handle specific logic in my use case, which is why I require it beyond this simple example below: enum ExampleA { A = 'A' } enum ExampleB { ...

Issue with setting value using setState in TypeScript - what's the problem?

Every time I attempt to update the value of currentRole, it appears highlighted in red. Here is a screenshot for reference: const Container: React.FC<ContainerProps> = ({ children }) => { const [role, setRole] = useState<string>(); useE ...

Angular: Navigating through two levels of fetched data from Firebase

I'm currently working on parsing retrieved data from Firebase within an Angular (Typescript) project. The structure of my JSON data in Firebase resembles the following: "customer" : { "customerId1" : { "documents" : { "documentId1" : { ...

Is there a way to identify when a user is returning to a previous page in Angular2

How can I detect if a user has pressed the back button in their browser to navigate back while using Angular? Currently, I am subscribing to router events to achieve this. constructor(private router: Router, private activatedRoute: ActivatedRoute) { ...

Data from the server isn't loading in Angular2

I have successfully developed a basic Java app using REST that returns a string value when accessed through a REST client. However, I am now facing an issue in fetching the string value using an Http REST client in Angular2. I have set up a service to retr ...

Unlocking the union of elements within a diverse array of objects

I have an array of fields that contain various types of input to be displayed on the user interface. const fields = [ { id: 'textInput_1', fieldType: 'text', }, { id: 'selectInput_1', fieldType: 'sel ...

The automatic type inference in Typescript is faulty

I am currently working with TypeScript version ^4.1.3 and have developed a REST API that deals with albums and art collections. Before sending the response to the web client, I make sure to remove the userId property from the collections. Below are my Alb ...

How can you type a collection of initialized class instances in Typescript when given an object containing classes?

Imagine having an object that resembles the following: const typeMap = {category1: Category1, category2: Category2} In this case, Category1 and Category2 refer to classes, and there could potentially be hundreds of different categories. Now I also have a ...

What is the process in Typescript for importing JSON files and dynamically searching for values based on keys?

When working with typescript 3.0.3, I encountered an issue while importing a json file in the following manner: import postalCodes from '../PostalCodes.json'; The json file has the structure shown below: { "555": { "code": 555, "city": "Sc ...

Create an object that may have any number of keys, but must have at least one key defined

Is there a way to accomplish this task? type Plant = "rose" | 'tulip' | 'daisy' type PlantCollection = { [p in Plant]?: number } const validPlantCollection: PlantCollection = { rose: 1, daisy: 2 } const emptyCollectionShouldBeRejec ...

Modifying webpack settings for a create-react-app based project: A step-by-step guide

After starting a new react project with create-react-app, I am looking to update the webpack configuration. However, I cannot seem to locate the webpack file. Should I be creating this file myself, or is there another process involved? As someone who is ...

Error: Unrecognized action type in Vuex

I've been encountering some major issues with vuex lately. For some reason, getters, actions, and mutations are not being recognized. In the code snippet below, although fetchFacilities is working fine, addFacility is throwing an error: [vuex] unknown ...

Creating a Modal using Typescript with NextJS

Currently, I'm working on creating a modal within my app using NextJS with Typescript. Unfortunately, I've been struggling to eliminate the warning associated with my modal selector. Can someone provide guidance on how to properly type this? cons ...

Having difficulty transferring types to and from a custom module?

I'm currently faced with an issue while working on a typescript module within a larger monorepo. I am having difficulty importing types from one package into another via node modules. The types are located at ./types, and my package.json contains a ke ...

Vue - Troubleshooting why components are not re-rendering after data updates with a method

Check out this simple vue component I created: <template> <div class="incrementor"> <p v-text="counter"></p> <button v-on:click="increment()">Increment</button> </div> </template> <script lan ...

Bovine without Redis to oversee queue operations

Can Bull (used for job management) be implemented without utilizing Redis? Here is a segment of my code: @Injectable() export class MailService { private queue: Bull.Queue; private readonly queueName = 'mail'; constructor() { ...

*ngFor is not rendering the array data and no error is being shown

Currently utilizing mongoDB's $filter aggregation feature, which has successfully generated the expected output from my query. However, I am encountering an issue with my HTML code as *ngFor is not displaying the data and no errors are being shown in ...