【问题标题】:ES6 modules' path resolution failureES6 模块的路径解析失败
【发布时间】:2018-01-29 21:19:29
【问题描述】:

我正在尝试使用 Chrome 60 中的新 ES6 功能(通过启用 Experimental Web Platform)。这是我项目的结构:

myproject
├── src
|   ├── mymodule.js
|   ├── dep1.js
|   ├── dep2.js
|   ├── dep3.js
├── pages
    ├── example
        ├── example1.html

这是我的页面example1.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>E6 6 experiments</title>
    <script type="module" src="../../src/mymodule.js"></script>
</head>
<body>
</body>
</html>

我设置Http-Server:

http-server /Users/myuser/myproject

这样我就有一个服务器正在运行并提供服务(为了避免与使用 file:/// 协议相关的 CORS 问题)。当我运行 Chrome 并在地址栏中输入:localhost://pages/example/example1.html 时,我收到此错误:

[Error] GET http://localhost:8080/src/dep1 
[Error] GET http://localhost:8080/src/dep2 
[Error] GET http://localhost:8080/src/dep3 

未加载依赖项

Developer Tools 窗口显示mymodule.js 已正确加载,但其依赖项不正确,路径不正确。文件mymodule.js开头有这3行:

import * as dep1 from "./dep1";
import * as dep2 from "./dep2";
import * as dep3 from "./dep3";

请记住,dep1.jsdep2.jsdep3.jsmymodule.js 位于同一位置。

我认为mymodule.js 可以很好地加载资源,否则如果它取决于服务器的根目录在哪里,这会变得很棘手。我在这里做错了什么?

【问题讨论】:

  • 嗯...我自己还没有尝试过,但我想知道导入是否出于某种原因实际上与文档相关(如在 html 中)?如果将导入更改为 import * as dep1 from "/src/dep1" 会发生什么?
  • 不,jk。服务器 404 错误另有说明。
  • @QuangdaoNguyen 同样的事情,同样的错误
  • 您可以直接从浏览器访问这些文件吗?
  • @QuangdaoNguyen 我可以得到它们,浏览器正确地获取了 javascript 文件,所以从 HTTP 服务器的角度来看它们是可用的

标签: javascript html ecmascript-6 es6-modules


【解决方案1】:

正如您在日志中看到的,相对路径已正确解析,该文件夹是预期的。问题是您的文件被称为dep1.js 而不是dep1 (等)。添加文件扩展名:

import * as dep1 from "./dep1.js";
import * as dep2 from "./dep2.js";
import * as dep3 from "./dep3.js";

或者,您可以将服务器配置为自动解决这些问题。

【讨论】:

  • @Andry 规范在哪里说的?
  • @Andry 那不是the spec。它也只说“由“my-module”标识的模块,经常“my-module.js””。也许他们应该明确说明“识别者”的工作方式取决于模块加载器 - 并且本机模块不会(还没有?)自动猜测扩展名。
  • 我的错我实际上想链接另一篇文章,实际规范,但通过第二次查看,我才意识到它就像你说的那样!非常感谢您的帮助
猜你喜欢
  • 2017-07-01
  • 2016-05-30
  • 1970-01-01
  • 1970-01-01
  • 2018-06-01
  • 1970-01-01
  • 2018-06-04
  • 2016-07-07
  • 2017-08-22
相关资源
最近更新 更多