javascriptasynchronousparcel

Top-level await does not work with Parcel


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"
}

Solution

  • 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>