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>
错误:
Uncaught SyntaxError: Unexpected token {
我正在使用 WebStorm 并在 Win7 的 Chrome 中运行该项目。
更新:
我将 index.html
内容更改为:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="a.js" type="module"></script>
</body>
</html>
错误:
Uncaught TypeError: Failed to resolve module specifier "b". Relative references must start with either "/", "./", or "../".
好像b.js
没有加载。
最佳答案
要使用 ES6 模块,您必须使用 type="module"
加载脚本 - 这确保不理解 ES6 模块的浏览器不会阻塞
接下来,要导入,您必须指定导入文件的路径和完整文件名
查看代码中的注释
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>
关于javascript - ES6 导入不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51720221/