-1

我正在学习 Javascript,但在使用导入/导出来模块化我的代码时遇到了问题。我试图通过阅读MDN Web Docs (Mozilla) 中的thisthis来了解这一点,但失败了。我知道这里已经有人问过了,但我无法解决这个问题

我在网络浏览器终端中遇到的错误是:Uncaught SyntaxError: Cannot use import statement outside a module

我将插入一个小例子来说明我如何尝试使用导入/导出:

索引.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
    </head>
    <body>
        <h1 class="title">Example</h1>
        <button class="title-button">Change title</button>
        <!--
            I tried adding this line but nothing has changed:
            <script type="module" src="module.js"></script>
        --->
        <script src='main.js'></script>
    </body>
</html>

模块.js

const changeTitle = newTitle => {
    const title = document.querySelector(".title");
    
    title.innerHTML = newTitle;
}

export { changeTitle };

主.js

import { changeTitle } from "./module";

const titleButton = document.querySelector(".title-button");

titleButton.addEventListener("click", () => {
    let newTitle = prompt("Enter new title:");
    
    changeTitle(newTitle);
});

注意:所有三个文件都在同一个文件夹中。

感谢您的时间。对不起,如果我在这篇文章中犯了错误。

4

1 回答 1

1

type="module"属性必须添加到使用 import 语句的脚本中(在本例中为main.js)。我的错误是尝试添加type="module"module.js不是main.js

于 2021-10-14T16:11:15.120 回答