0

I have a js class inside movie.js that I'd like to import to my code on main.js where I plan to work with it. I've been struggling with the following error: SyntaxError: import declarations may only appear at top level of a module

I have already put the type="module" tag in the HTML and checked if the import/export are in the right place. I saw another answers to similar questions, but none solved the case.

(This is the relevant HTML)

<html>
 <head>
  <script src='main.js' async></script>
  <script src='movie.js' type="module" ></script>
 </head>
 <body>
  <a class="btn">Search</a>
 </body>
</html>
import Movie from './movie.js';

const btnSearch = document.querySelector(".btn");


btnSearch.addEventListener('click', function () {
    let filmeTeste = new Movie("The Lego Movie", 2014, "tt1490017", "Movie", "https://m.media-amazon.com/images/M/MV5BMTg4MDk1ODExN15BMl5BanBnXkFtZTgwNzIyNjg3MDE@._V1_SX300.jpg");
    console.log(`object test ${filmeTeste}`);
});
class Movie {
    constructor(title, year, imdbID, type, poster){
        this.title = title;
        this.year = year;
        this.imdbID = imdbID;
        this.type = type;
        this.poster = poster;
    };
}
export default Movie;

I expect to get the object printed in the console, but right now it only shows me SyntaxError: import declarations may only appear at top level of a module main.js:1

2

1 Answer 1

2

You also need to add the type="module" to your other <script> tag, because it also uses modules.

<script src="main.js" async type="module"></script>
<script src="movie.js" type="module" ></script>
Sign up to request clarification or add additional context in comments.

2 Comments

The <script src="movie.js" type="module" ></script> also shouldn't be needed in the first place, since main.js already imports/loads it.
Yes @loganfsmyth, that's true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.