顶级等待不适用于 Parcel

Top-level await does not work with Parcel

顶级 await 当我在实时服务器插件中 运行 它时正常工作(或 edit live Webstorm IDE);但是,当我使用 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"
}

看完 Parcel Doc 我找到了答案。

  1. 阅读here。使用 <script type="module"> 元素引用模块。

  2. 删除 dist 文件夹(如果存在),然后使用这些命令:

    npx parcel build index.html
    npx parcel index.html
    

或者设置一个脚本来构建您的应用程序。你可以阅读 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"
  }
}

现在使用这些命令:

npm:

npm run build
npm run start

纱线:

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>