【问题标题】:ES6 imports doesn't workES6 导入不起作用
【发布时间】:2018-08-07 06:31:19
【问题描述】:

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>

错误:

未捕获的类型错误:无法解析模块说明符“b”。相对引用必须以“/”、“./”或“../”开头。

好像b.js没有加载。

【问题讨论】:

  • 您需要在脚本标签中包含type="module"。其他资源 (b.js) 必须对页面可用。
  • 这个问题很可能是 ES6 模块在 javascript 中工作,您需要脚本标签上的 type="module" 属性
  • Webstorm 与此无关。它只是一个 IDE。它实际上不会运行代码
  • @AshishGaur 甚至没有接近重复
  • 抱歉,没看过a.js ... import {x} from './b.js'

标签: javascript


【解决方案1】:

要使用 ES6 模块,您必须使用 type="module" 加载脚本 - 这可以确保不理解 ES6 模块的浏览器不会卡住它

接下来,要导入,您必须指定导入文件的路径和完整文件名

查看代码中的 cmets

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>

【讨论】:

  • 工作。为什么我需要添加./.js?我在 Mozilla 的文档中没有看到。
  • 您在 Mozilla 中看到文档说您可以关闭文件扩展名吗?
  • 嗯?您必须在文档中明确指定文件名。请查看此文档中module-name 的描述:import syntax
  • 我的错。我完全错了。感谢您的帮助。 (我没有看到 Mozilla 在前缀中添加了 .。-为什么?)
  • This is often a relative or absolute path name ...相对路径至少以.开头 ...绝对路径以/开头 ...所以就我而言,名称必须有一个路径组件阅读它 - 除非您当然知道相对路径和绝对路径,否则不清楚
猜你喜欢
  • 2018-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-03
  • 1970-01-01
  • 2016-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多