javascript - ES6 导入不起作用

标签 javascript

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 "../". enter image description here

好像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/

相关文章:

javascript - 谷歌脚本编辑器 OnChange 触发器不工作

用于验证 URI 和/或端口的 JavaScript 正则表达式

javascript - Bootstrap Dropdown 在升级后不起作用

javascript - jquery删除表行帮助

javascript - 如何循环嵌套子结构?

javascript - 禁用临时滚动功能

javascript - Reactjs:setState总是失败并在componentDidMount中返回undefined

javascript - 代码返回 NAN

javascript - 使用 jquery/javascript 从 Yahoo 管道解析 json

javascript - 如何在 HTML 页面上隐藏/显示图像