ES6 export,import报错


问题描述:

现有两个文件:

profile.js

const firstName = 'Michael';
const lastName = 'Jackson';
const year = 2018;
export {firstName, lastName, year}

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    import {firstName, lastName, year} from './profile.js';
    console.log(firstName);
    console.log(lastName);
    console.log(year);
</script>
</body>
</html>

运行结果:

test.html:9 Uncaught SyntaxError: Unexpected token {

问题解答:

在HTML文件中不能使用export,import,需要在webpack构建项目中使用,并且只作用于.vue.js文件。

如果非要使用且浏览器支持ES6,需要加上 type="module"

<script type="module">
    import {firstName, lastName, year} from './profile.js';
    console.log(firstName);
    console.log(lastName);
    console.log(year);
</script>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM