在html文件中的script标签引入 ES6 的模块,
浏览器中打开该html文件,
出现Uncaught SyntaxError: Cannot use import statement outside a module 报错.
index.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="main.js"></script>
</body>
</html>
main.js文件:
import string from './CSS.js'
const player = {
console.log('hi')
},
events : {
console.log('hi')
}
CSS.js文件:
const string = `.skin *{ margin: 0; padding: 0;box-sizing: border-box;}
.skin *::before{box-sizing: border-box;}
.skin *::after{box-sizing: border-box;}
body{
background-color:#dadada ;
}
export default string;
这里报错的原因是用了 ES6 语法, 浏览器默认将它作为JS解析会出现问题,
需要将它作为模块导入,script标签默认type="text/javascript",
需要改为type="module"。
更改后的index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="module" src="main.js"></script>
</body>
</html>