unused import statement解决方法(详细分析解决Uncaught SyntaxError: Cannot use import statement outside a module (at …)的错误)
1. 复现错误
今天在学习es6时 ,启动页面后 ,却报出如下图错误:
即Uncaught SyntaxError: Cannot use import statement outside a module (at module.html?_ijt=vfvtohb23jt1tj3r4ad3a0t82v:19:5) 。
2. 分析错误
点开错误信息 ,定位到错误的位置 ,如下图所示:
也就是说 ,在导入包时 ,出现了这个错误 。
于是 ,查看我的module.html页面 ,如下代码所示:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>引入外部module.ts文件</title> <style type="text/css"> * { margin: 0; padding: 0; } html { background-color: #1b6d85; } </style> </head> <body> </body> <script type="text/javascript"> import {btn_onclick, multiple, Person} from "moduleTest/module.js" const btnClick = btn_onclick; console.log(btnClick) console.log("multiple(2, 3)=", multiple(2, 3)) const person = new Person({"id": 1, name: "super先生"}) console.log("person=", person) console.log("person.getName=", person.getName()); </script> </html>这个页面没有看出存在什么样的问题 ,再去排查我的module.js模块文件 ,检查有误使用export导出模块 ,如下代码所示:
/** * 定义一个button弹框 */ const btn_onclick = () => window.alert("点击了button按钮 ,哈哈 。 。 。 。"); /** * 两数相乘,比如 2 * 3 = 6 * @param num1 乘数 * @param num2 被乘数 * @return 返回两数之积 */ const multiple = (num1, num2) => num1 * num2; /** * 定义一个Person实体类 */ class Person { constructor(obj) { this.id = obj.id this.name = obj.name; } getName() { return this.name; } } //导出 export {btn_onclick, multiple, Person}如上代码可知 ,我已使用export导出模块了 ,那问题出现在哪里呢?
于是,查阅相关资料可知:对于es6的语法 ,我们使用import导入模块的语法时 ,需要将html中声明的<script>标签的类型(type)指定为module ,而非text/javascript 。
3. 解决错误
因而 ,通过资料可知 ,我们需要将module.html中的<script type="text/javascript">修改成<script type="module"> ,如下图所示:
如上修改后 ,即能输出正确的结果 ,如下图所示:
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!