当我在 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 .
阅读here .使用
<script type="module">
引用模块的元素。删除
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/