In a parcel-bundled browser extension, I have set up my popup’s HTML to load a script tag with the attribute type="module"
, like so:
// popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Popup</title>
<link rel="stylesheet" href="popup.css">
</head>
<body>
<h1>My web extension</h1>
<script type="module" src="popup.js"></script>
<div id="app"></div>
</body>
</html>
// popup.js
import { setNameSpace, getTab } from "./helpers.js"
import { startStore } from "./store.js"
setNameSpace()
const store = startStore()
const state = await store.get()
As specified in the official documentation, this should allow use of the await
keyword before async funcs at the top level:
Tip: You can use top level await by adding type="module" to the script tag.
…but popup.js still gives the error:
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
I can get around this by wrapping in a self-invoking async function, but why is this extra workaround needed?
// popup.js
...
(async ()=> {
const store = startStore()
const state = await store.get()
})()
My package.json
, for reference:
{
"name": "my-web-extension",
"version": "0.0.1",
"description": "My web extension",
"scripts": {
"watch:chrome": "parcel watch src/chrome/manifest.json --dist-dir dist-chrome --host localhost --config @parcel/config-webextension",
"build:chrome": "parcel build src/chrome/manifest.json --dist-dir dist-chrome --config @parcel/config-webextension",
"watch:firefox": "parcel watch src/firefox/manifest.json --dist-dir dist-firefox --host localhost --config @parcel/config-webextension",
"build:firefox": "parcel build src/firefox/manifest.json --dist-dir dist-firefox --config @parcel/config-webextension"
},
"devDependencies": {
"@parcel/config-webextension": "^2.10.3",
"parcel": "^2.10.3"
}
}