js文件无法正确导入js模块,即使在html上插入type =“ module”

时间:2019-06-26 00:31:23

标签: javascript html object ecmascript-6 es6-class

movie.js中有一个js类,我想将其导入到我打算使用它的main.js上的代码中。 我一直在努力解决以下错误: SyntaxError:导入声明只能出现在模块的顶层

我已经将type =“ module”标记放入HTML中,并检查导入/导出是否在正确的位置。我看到了类似问题的另一个答案,但没有一个解决问题。

(这是相关的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;

我希望在控制台中打印该对象,但是现在它仅向我显示SyntaxError:导入声明可能仅出现在模块main.js:1的顶层

1 个答案:

答案 0 :(得分:1)

您还需要将type="module"添加到其他<script>标记中,因为它也使用模块。

<script src="main.js" async type="module"></script>
<script src="movie.js" type="module" ></script>