简体   繁体   中英

ES6 imports doesn't work

b.js :

const x = 1;
export {x};

a.js :

import {x} from 'b'; // <<-- ERROR
console.log(x);

index.html :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="a.js"></script>
</body>
</html>

Error:

Uncaught SyntaxError: Unexpected token {

I'm using WebStorm and running the project in Chrome in Win7.


Update:

I changed index.html content to:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="a.js" type="module"></script>
</body>
</html>

Error:

Uncaught TypeError: Failed to resolve module specifier "b". Relative references must start with either "/", "./", or "../". 在此输入图像描述

It seems that b.js is not loaded.

To use ES6 modules, you have to load the script using type="module" - this ensures that browsers that do not understand ES6 modules won't choke on it

Next, to import, you must specify path and full filename of the imported file

See comments in code

b.js

const x = 1;
export {x};

a.js

// specify the path and full filename below
import {x} from './b.js'; // <<-- NO ERROR NOW
console.log(x);

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!-- add type="module" -->
<script src="a.js" type="module"></script>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM