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>

 

posted @ 2018-12-13 10:56  寒爵  阅读(2097)  评论(0编辑  收藏  举报