gpt4 book ai didi

javascript - 顶级等待不适用于 Parcel

转载 作者:行者123 更新时间:2023-12-05 08:03:57 25 4
gpt4 key购买 nike

当我在 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.htmlnpx 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 buildnpm run start

yarn:

yarn buildyarn 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com