Top-level await does not work with Parcel
Asked Answered
S

1

6

Top level await works correctly when I run it in live server plugin (or edit live Webstorm IDE); however, that code throws an error when I deploy it with npx parcel index.html.

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules

const res =  await Promise.resolve('hi there');

console.log(res)
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <script type="module" defer src="script.js"></script>
    <title>parcel and top-level-await</title>
  </head>
  <body>
  </body>
</html>
   {
  "devDependencies": {
    "parcel": "^2.2.1"
  },
  "name": "top-level-await",
  "version": "1.0.0",
  "main": "index.js",
  "author": "elmi-elmi",
  "license": "MIT"
}
Spittoon answered 30/1, 2022 at 14:17 Comment(2)
@Terry - Top-level await is broadly supported by modern browsers.Peonir
By default, Parcel bundles your code into a single script (not a module), but top-level await can only be used in modules, so it doesn't work. You have to tell Parcel to output a module file instead. There seems to be an outputFormat option for controlling it, but I don't use Parcel and didn't get it working in the few minutes of fiddling I did. There's also this open issue about TLA.Peonir
S
-2

I found the answer after reading Parcel Doc.

  1. Read here. Use a <script type="module"> element to reference a module.

  2. Remove the dist folder if it exists, then use these commands:

    npx parcel build index.html
    npx parcel index.html
    

Or set up a script to build your app. You can read here.

So far, we’ve been running the parcel CLI directly, but it can be useful to create some scripts in your package.json file to make this easier.

{
  "name": "my-project",
  "source": "src/index.html",
  "scripts": {
    "start": "parcel",
    "build": "parcel build"
  },
  "devDependencies": {
    "parcel": "latest"
  }
}

Now use these commands:

npm:

npm run build
npm run start

yarn:

yarn build
yarn start
const res = await Promise.resolve('hi there');

console.log(res)
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <script type="module" defer src="script.js"></script>
    <title>parcel and top-level-await</title>
  </head>
  <body>
  </body>
</html>
Spittoon answered 31/1, 2022 at 8:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.