Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

Get error to build my project in Vite - Top-level await is not available in the configured target environment

Writer Matthew Harrington

I try to build my project in vite,

my project -

I run npm run dev and all work.

but when I run to build it I get an error.

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

I try to fetch a data and think here is the problem link (line 22+23) -

const shopsData = await fetchStarbucksShops();

If anyone encounters this curse I would be happy to help

4 Answers

Top-level-await is a new es feature which wouldn't run in old browsers. If you believe your users use relatively new versions and can handle top-level-await, you can set up vite.config like this:

export default defineConfig({ build: { target: 'esnext' //browsers can handle the latest ES features }
})

or

export default defineConfig({ esbuild: { supported: { 'top-level-await': true //browsers can handle top-level-await features }, }
})
1

First, check this; . If you can't find an answer try this to create a big fat async function that executes itself to decrease the level of your await;

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

It might not work. You should avoid top-level await somehow, whether use await inside the async function, or use .then()

1

For those who experience the same issue in the both dev and build commands, add the following

// vite.config.js
optimizeDeps: { esbuildOptions: { target: 'esnext' } }, build: { target: 'esnext' }

on VITE v4.5.0 only Maduka Jayalath answer works. Two other solutions didn't work for me.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.