Encountering an issue while building my project in Vite - The configured target environment does not support top-level await

I attempted to compile my project using vite,

my project - https://github.com/yakovcohen4/starbucks-openlayers

Running npm run dev works fine.

However, I encountered an error when trying to build it.

Error message:

Top-level await is not available in the configured target environment ("chrome87", "edge88", "es2019", "firefox78", "safari13.1")

I suspect the issue lies in trying to fetch data at this link (line 22+23) - https://github.com/yakovcohen4/starbucks-openlayers/blob/main/starbucks-project/src/main.ts

const shopsData = await fetchStarbucksShops();

If anyone has faced this problem before, I would appreciate any help.

Answer №1

Introducing top-level-await, a cutting-edge ES feature that may not be compatible with outdated browsers. If you have confidence that your audience is on more recent browser versions and can handle top-level-await, you can configure your vite.config file as follows:

export default defineConfig({
  build: {
    target: 'esnext' //ensure support for the latest ES features in modern browsers 
  }
})

or

export default defineConfig({
  esbuild: {
    supported: {
      'top-level-await': true //facilitating compatibility with top-level-await features in browsers
    },
  }
})

Answer №2

If you are facing the same issue with both development and build commands, try adding the following code snippet to your vite.config.js file:

// vite.config.js
export default defineConfig({
  optimizeDeps: {
    esbuildOptions: {
      target: 'esnext'
    }
  },
  build: {
    target: 'esnext'
  },
  // more config options ...
})

Answer №3

"Top-level await" is a feature expected in ES2022. To check browser support, visit CanIUse.com - await: top-level.

Option 1 - If your supported browsers include top-level await, you can overlook the error using the Vite config provided below. This method specifically targets disabling the build error for this ES feature without masking potential other breaking changes.

To address source code issues causing the error:

export default defineConfig({
  esbuild: {
    supported: {
      'top-level-await': true
    },
  },
});

To tackle errors from specific dependencies like pdfjs-dist:

export default defineConfig({
  optimizeDeps: {
    include: ["pdfjs-dist"],
    esbuildOptions: {
      supported: {
        "top-level-await": true
      },
    },
  },
});

Option 2 - Another approach is to use a Vite plugin such as vite-plugin-top-level-await to eliminate top level awaits. Keep in mind that adding another dependency may complicate debugging and affect production code.

Answer №4

Before moving forward, make sure to review the following link: https://github.com/vitejs/vite/issues/6985. If you're unable to find a solution, attempt creating a large asynchronous function that runs itself to reduce the reliance on await statements;

    (async () => {
    export const shopsData: shopType[] = await fetchStarbucksShops();
    export const countryGeoData: countryGeoDataType = await fetchGeoJsonCountry();
    .
    .
    .
    .
    .
     })();

This method may not be successful. It is recommended to avoid using top-level awaits by incorporating them within the asynchronous function or utilizing .then() instead.

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

Angular click switch Component keeps track of its previous state

I recently developed an Angular component that consists of a button and an icon. One key requirement is for each instance of this component to retain its own status. For example, let's say we have three instances in the app.component.html: <app-v ...

Could JOI be used to validate unidentified keys within nested data structures?

I've developed a middleware that uses Joi to validate incoming requests. export default (schema: any) => async (req: Request, res: Response, next: NextFunction) => { try { const validation = schema.validate(req, { abortEarly: false }) ...

Guidelines for cycling through a series of HTTP requests and effectively saving the data from each cycle into an array

Utilizing Spotify's API search feature, I am working with an array of SongSearchParams that consist of title and artist parameters: export class SongSearchParams { public title: string; public artist: string; constructor(title: string, a ...

I am having trouble with updating an array in React useState. Every time I try to make changes, it keeps reverting back to the initial state. What could

My current task involves managing a state array called monthlyIncidents, which contains 12 numbers that need to be updated under certain conditions. I attempted to update the elements by copying the array, modifying the specific element, and then updating ...

Trying to create a function in TypeScript that works like lodash's "bindKey"?

I am looking to create a function that serves as a shortcut for obj.func.bind(obj). It should work like this: const bound = <...>(obj: ..., fnKey: ...) : ... => obj[fnKey].bind(obj); const obj = { a: "abc", b() { console.log(thi ...

Searching and adding new elements to a sorted array of objects using binary insertion algorithm

I'm currently working on implementing a method to insert an object into a sorted array using binary search to determine the correct index for the new object. You can view the code on codesanbox The array I have is sorted using the following comparis ...

Using AWS StepFunctions to add a prefix to an input string

How can I use TypeScript and CDK to create a task that prefixes one specific field in the input while leaving the rest unchanged? Input: { "field1": "foo", "field2": "bar" } Desired output: { "field1" ...

"Upon the addition of a child, no response is being given

My database structure resembles the following: https://i.sstatic.net/duWdk.png /* formsById formId usersList userId */ I am trying to retrieve a list of all users (usersList) associated with a specific formId. Below is my method ...

When assigning JSON to a class object, the local functions within the class became damaged

This is a demonstration of Object Oriented Programming in JavaScript where we have a parent Class called Book with a child class named PriceDetails. export class Book { name: String; author: String; series: String; priceDetails: Array<Price> ...

Encountering Errno: -4071 with EINVAL in NextJS, issues persisting with resolution

I've encountered an issue while working on my Next.js project today. I'm unable to start the project using npm run dev and keep receiving this error: [Error: EINVAL: invalid argument, readlink 'C:\Users\cxXni\OneDrive\Doc ...

The type NgxMatDatetimePicker cannot be assigned to type MatDatepickerBase

Today marks the launch of my latest Angular project built with Angular 11.0.0. I decided to incorporate the @angular-material-components/datetime-picker package, which is now reflected in my package.json file: ... "@angular/core": "~11.0.0&q ...

Define the type as an array of any attributes from an interface

Looking for a solution: interface Details { id: string; groups: Group[]; name: string; total: number; open: boolean; debug: boolean; demo: boolean; registered: boolean; } I'm seeking a way to create an array type with property names f ...

Links do not open in a new tab or new window as intended

I am facing an issue where I can navigate to all links, pages, or components from the base URL, but I cannot open a specific URL like "http://localhost:4200/home/dashboard" in a new tab. Instead, it just shows a blank page. It is worth noting that even wh ...

Incorporate Select2 functionality within the Angular2 application

I'm currently working on incorporating the Select2 plugin into my Angular2 application. Successfully, I have managed to set up select2 and transform my multiple select fields as expected. However, I am now facing a challenge in retrieving the selected ...

The navigate function in this.router is not functioning as intended

While working with Angular 8, I encountered routing issues specifically when using lazy-loaded child modules. app-routing.module.ts ... const routes: Routes = [ { path: :id, component: ParentComponent, children: [ { path: ...

Having trouble implementing two-way binding in Angular for a specialized component?

Within my view component, I am fetching data from a service and setting it as a property. Custom components then use these fields to display the data. Everything seems to be working fine so far. <app-textbox [caption]="'First name'" ...

Wait for a minimum of X milliseconds using RxJS

I'm attempting to achieve a specific functionality using RxJS: Trigger an event Make an API call Upon receiving the API response, do one of the following: Wait for at least X milliseconds after triggering the event If X milliseconds have already p ...

Showing Nested Numerical Objects Post RequestBeing Made

Currently, I am facing an issue with accessing nested objects referred to by numbers. After making a service call to retrieve a JSON object, I mapped each field to another object which will be used for displaying the fields in HTML. The problem arises whe ...

Ensuring the safety of generic types in Typescript

Typescript is known for its structured typing, which is a result of the dynamic nature of Javascript. This means that features like generics are not the same as in other languages with nominal type systems. So, how can we enforce type safety with generics, ...

Utilize API with unique characters in the URL

Attempting to make an API call from the front end using this API: http://localhost/search?userName=... get(endpoint: string, responseType = 'json', params: HttpParams = null): Observable<any> { let url = this.getHost() + endpoint; i ...