[英]ES6 imports doesn't work
b.js
: b.js
:
const x = 1;
export {x};
a.js
: a.js
:
import {x} from 'b'; // <<-- ERROR
console.log(x);
index.html
: 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 {
未捕获的SyntaxError:意外的令牌{
I'm using WebStorm and running the project in Chrome in Win7. 我正在使用WebStorm并在Win7中运行Chrome中的项目。
I changed index.html
content to: 我将
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>
Error: 错误:
Uncaught TypeError: Failed to resolve module specifier "b".
未捕获的TypeError:无法解析模块说明符“b”。 Relative references must start with either "/", "./", or "../".
相对引用必须以“/”,“./”或“../”开头。
![]()
It seems that b.js
is not loaded. 似乎没有加载
b.js
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 要使用ES6模块,您必须使用
type="module"
加载脚本 - 这可以确保不了解ES6模块的浏览器不会阻塞它
Next, to import, you must specify path and full filename of the imported file 接下来,要导入,必须指定导入文件的路径和完整文件名
See comments in code 请参阅代码中的注释
const x = 1;
export {x};
// specify the path and full filename below
import {x} from './b.js'; // <<-- NO ERROR NOW
console.log(x);
<!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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.