I have a top-level await
in a script.js module, which is the main module linked to my index.html. The <script>
tag has type="module"
.
I have installed parcel locally in the project’s environment. When I run npx parcel index.js
, parcel creates and serves development files from the dist folder. The new .js file/s in the dist folder is linked to the new index.html as a regular script instead of a module (It doesn’t have type="module"
. E.g. <script src="/index.f5c48570.js" defer=""></script>
). Because of that, the top-level await doesn’t work. I want parcel to link script.js as a module to index.html, not as a script when I run npx parcel index.html
. I’ve tried many things, fiddled with the configurations in package.json, and read the docs but nothing seems to work.
However, when I run npx parcel build index.html
, the .js file is added as a module to index.js, as expected, likely because I’ve set browserslist
to "Chrome 80"
in package.json. I want npx parcel index.html
to do the same, but it doesn’t.
Following is my code:
package.json (all dependencies are installed locally):
{
"name": "my-project",
"version": "1.0.0",
"browserslist": "Chrome 80",
"targets": {
"modern": {
"engines": {
"browsers": "Chrome 80"
}
}
},
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "Rishi",
"license": "ISC",
"description": "",
"dependencies": {
"leaflet": "^1.9.4",
"lodash-es": "^4.17.21"
},
"devDependencies": {
"parcel": "^2.12.0"
}
}
script.js:
import cloneDeep from './node_modules/lodash-es/cloneDeep.js';
const state = {
cart: [
{ product: 'bread', quantity: 5 },
{ product: 'apples', quantity: 10 },
],
user: { loggedIn: false },
};
const stateCloneDeep = cloneDeep(state);
console.log(stateCloneDeep);
const getLastPost = async function () {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await res.json();
return { title: data.at(-1).title, text: data.at(-1).body };
};
const lastPost = await getLastPost(); // Top-level await
console.log(lastPost);
index.html:
<!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" src="script.js"></script>
<title>Modern JavaScript Development: Modules and Tooling</title>
<style>
/* ---- SOME STYLES ---- */
</style>
</head>
<body>
<h1>My Project</h1>
</body>
</html>