我正在尝试制作简单的 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/