I’m trying to define an array in a separate file and import it into my main js file.
I was getting the error “Uncaught SyntaxError: import declarations may only appear at top level of a module” and I found some forum posts and docs that said I need to make both js files modules in the HTML:
<script src="script.js" type="module"></script>
<script src="module.js" type="module"></script>
This worked in a small example project, but when I tried to do this to my real project the functions stop working and come back as “undefined”.
Does anyone have any insight here?
This is my small test project that seems to work fine:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="" />
</head>
<body>
<script src="script.js" type="module"></script>
<script src="module.js" type="module"></script>
</body>
</html>
script.js
import { arrayFour } from "./module.js";
console.log(arrayFour);
const functionOne = () => {
console.log("funcion one");
console.log(arrayFour);
};
function functionTwo() {
console.log("funcion two");
console.log(arrayFour);
}
functionOne();
functionTwo();
module.js
const arrayFour = [1, 2, 3, 4];
export { arrayFour };
This all worked as expected, and the functions work. However when I do the same thing with my larger project the functions become undefined. I think it might have something to do with global scope vs script scope, but my small test project works fine.
Here’s the current code for the larger project:
https://github.com/pkdvalis/MBC-Search
I’m trying to import the long array previously
from another file. When I implement the import locally I get these errors:
Uncaught ReferenceError: searchFor is not defined
onclick http://127.0.0.1:3000/index.html:1
index.html:1:1
Uncaught ReferenceError: getDetails is not defined
onclick http://127.0.0.1:3000/index.html:1
index.html:1:1
These are the changes I make:
script.js
import { previouslyList } from './previouslylist.js'
let previously = previouslyList;
//comment out the existing let previously
index.html
<script src="previouslylist.js" type="module"></script>
<script src="script.js" type="module"></script>
previouslylist.js
const previouslyList = [
{ title: "The Pelican Brief", author: "John Grisham" },
{ title: "Eat, Pray, Love", author: "Elizabeth Gilbert" },
// etc etc
{ title: "L.A. Candy", author: "Lauren Conrad" },
];
export { previouslyList };
Everything is working fine, and when I make these changes all of the sudden the functions stop working. If I remove type="module"
it’s ok but then I get the "Uncaught SyntaxError: import declarations may only appear at top level of a module"
error.
Cannot understand why this is happening, any help appreciated!