这个问题在这里已经有了答案:
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/