5

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"
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
elmi
  • 166
  • 1
  • 9
  • @Terry - [Top-level await is broadly supported by modern browsers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#browser_compatibility). – T.J. Crowder Jan 30 '22 at 14:22
  • 1
    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`](https://parceljs.org/features/targets/#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](https://github.com/parcel-bundler/parcel/issues/4028) about TLA. – T.J. Crowder Jan 30 '22 at 14:35

1 Answers1

-1

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>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
elmi
  • 166
  • 1
  • 9