使用es中export语法,发现没出结果,报错提示:Uncaught SyntaxError: Cannot use import statement outside a module
出现此问题的原因是:script标签默认的type属性是 type=“text/javascript”,将此属性改为 type="module"即可解决

案例如下:
1.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script type="module" src="./2.js"></script>
</body>
</html>
1.js:
export default function test(a,b){
return a + b
}
2.js:
import getTest from './1.js'
console.log(getTest(1,2))
本文档介绍了在HTML中使用ES模块时遇到的`UncaughtSyntaxError: Cannot use import statement outside a module`错误。问题源于script标签默认type属性为`text/javascript`,需要更改为`module`。通过修改1.html中的script标签类型,可以成功引入并执行1.js中的export默认函数。示例中展示了如何在2.js中导入并调用1.js的test函数,从而正确运行代码。
6667

被折叠的 条评论
为什么被折叠?



