Uncaught SyntaxError: Cannot use import statement outside a module

1、错误描述

Uncaught SyntaxError: Cannot use import statement outside a module

2、错误原因

      定义了一个JavaScript文件,声明几个变量,利用模块化导出变量

let name = '张华'
let age = 23
let sex = '女'

export {name, age, sex}

       接着,在页面文件中直接导入import;打开浏览器访问页面,控制台出现报错

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="../js/a1.js"></script>
		<script src="../js/a2.js"></script>
		<script>
			import {name, age, sex} from '../js/a3.js'
			console.log(name,age,sex)
		</script>
	</head>
	<body>
	</body>
</html>

3、解决办法

      需要在script标签上添加属性type="module"

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="../js/a1.js"></script>
		<script src="../js/a2.js"></script>
		<script type="module">
			import {name, age, sex} from '../js/a3.js'
			console.log(name,age,sex)
		</script>
	</head>
	<body>
	</body>
</html>

 

©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页