13

I try to build my project in vite,

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

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) - https://github.com/yakovcohen4/starbucks-openlayers/blob/main/starbucks-project/src/main.ts

const shopsData = await fetchStarbucksShops();

If anyone encounters this curse I would be happy to help

yakov
  • 331
  • 5
  • 12

2 Answers2

14

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
    },
  }
}
ForcedFakeLaugh
  • 567
  • 1
  • 9
  • 20
1

First, check this; https://github.com/vitejs/vite/issues/6985. 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()

Cengiz
  • 162
  • 9
  • Thank you very much, in the end, I saw this repo and it helps me ... (thank you for your answer) – yakov Jun 17 '22 at 08:26