javascript - 顶级等待不适用于 Parcel

标签 javascript asynchronous parcel

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

最佳答案

看完包裹我找到了答案Doc .

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

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

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

现在使用这些命令:

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>

关于javascript - 顶级等待不适用于 Parcel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70915492/

相关文章:

javascript - 使用javascript如何在设定时间后打破while循环?

javascript - 从已解决的 Promise 数组中获取值

java - Parcelable 类不会创建可分割对象

javascript - 带有 jQ​​uery AJAX 的 WCF REST - 删除/解决同源策略

javascript - 使用纯 JS 并使用 nextElementSibling 制作多层 Accordion

javascript - 导出异步等待变量并在 JS 中完成 "awaiting"后将其导入另一个文件

c# - 跟踪 c#/.NET 任务流

android - 在 Android 中制作自定义 java 对象 Parcelable

javascript - 此实验性语法需要启用以下解析器插件之一 : 'classPrivateProperties, classPrivateMethods'

javascript - 匿名函数javaScript的removeEventListener