gpt4 book ai didi

javascript - 我无法修复 "Uncaught SyntaxError: Cannot use import statement outside a module"的问题

转载 作者:行者123 更新时间:2023-12-01 15:16:39 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

(5 个回答)


2年前关闭。




我在一个文件夹中有“三个”文件
1. 索引 .html
2. 索引 .js
3. helper .js

我想从 helper.js 导出代码并将代码导入 index.js (我已经将 index.js 链接到 index.html )。

我确实喜欢
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">
<title>Document</title>
</head>
<body>

<button id="btn">click</button>


<script src="./index.js"></script>
</body>
</html>


index.js
import btn from './helper'

btn.addEventListener('click', function () {
window.alert('i am clicked')
})


最后是 helper.js
export let btn = document.getElementById('btn')


然后我运行 index.html chrome浏览器中的文件。

Chrome 浏览器在控制台中显示此消息。

未捕获的语法错误:无法在模块外使用 import 语句

请告诉我该如何解决这个问题。我在 google 和 youtube 上搜索,我做了他们展示的同样的事情。结果,浏览器显示该消息。

最佳答案

您需要在模块中包含导入:

尝试这个:

<script type="module">
import btn from './helper'
</script>

引用: ES Modules in Browsers

关于javascript - 我无法修复 "Uncaught SyntaxError: Cannot use import statement outside a module"的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58206020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com