javascript - ES 模块导入不起作用

标签 javascript

我正在尝试制作简单的 Vanilla ES 导入导出示例。

索引.js

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <script type="module" src="main.js"></script>
</head>
<body>

</body>
</html>

主要.js

import {foo} from './mathModule';

console.log(foo);

数学模块.js

export const foo = Math.sqrt(2);

当我运行这个页面时出现错误

main.js:1 GET http://[page].net/test/mathModule 404 (Not Found)

编辑: 项目结构

  • 测试
    • index.html
    • main.js
    • mathModule.js

最佳答案

import 需要一个完全限定的 URL。除非绝对 URL 上没有扩展名,否则您不能省略扩展名。

因此根据您的示例判断使用:

import {foo} from './mathModule.js';

作为 Nimeshka Srimal 捕获了,看起来扩展要求因实现而异。 Firefox 会自动附加 .js,但 Chrome 和 Safari 需要实际地址。

我正在查看规范,15.2.2 Imports ,并且似乎没有关于实现者是否应该自动附加扩展名的任何规范。

另外,作为 ASDFGerte the MDN docs on import指出:

The module to import from. This is often a relative or absolute path name to the .js file containing the module. Certain bundlers may permit or require the use of the extension; check your environment. Only single quotes and double quotes Strings are allowed.

关于javascript - ES 模块导入不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51387238/

相关文章:

javascript - Nodejs 和 Express 中的动态配置文件

javascript - 如何给函数下的属性赋值?

javascript - Cordova "hidekeyboard"事件在 Cordova 5.0 中不起作用

javascript - 使用 jQuery .append() 后刷新表

javascript - 内联进度条动画,更改触发器以从加载滚动?

Javascript - 获取文本区域的确切值

javascript - 有没有办法在 IE 中获取边框半径和渐变背景?

javascript - 如何在更改幻灯片之前设置延迟?

javascript - 有什么好的 Javascript 图形库吗?

javascript - 如何将带有查询字符串的当前 Url 传递给 MVC 中的 Html.ActionLink() 函数