我正在尝试将模块导入到我的index.html 文件中。
这是代码:
// Index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div></div>
<script type="module" src="module.js"></script>
<script type="text/javascript">
import { addTextToBody } from 'module.js';
addTextToBody('some text here');
</script>
</body>
</html>
还有 js:
export function addTextToBody(text) {
const div = document.createElement('div');
div.textContent = text;
document.body.appendChild(div);
}
我收到这些错误:
未捕获的语法错误:意外的标记 { - 第 18 行
从源“null”访问“module.js”中的脚本已被 CORS 策略阻止:响应无效。因此不允许访问源“null”。
我该如何解决这个问题?
最佳答案
-
module.js
应该是./module.js
- 您不需要在页面开头导入模块(但您可以)。
- 使用
import
要求脚本的类型为module
不仅仅是导入的脚本。 - 您应该将模块导入放置在
<head>
中(一开始)。
以下示例有效(我删除了不必要的部分):
<!-- index.html -->
<meta charset="utf-8">
<script type="module">
import { addTextToBody } from './module.js';
addTextToBody('some text here');
</script>
// module.js
export function addTextToBody(text) {
const div = document.createElement('div');
div.textContent = text;
document.body.appendChild(div);
}
上面提供的代码适用于 Firefox,但不适用于 Chrome。看来您正在使用 Chrome(我认为从您的错误消息来看)。 Chrome 严格禁止访问 file://
的资源协议(protocol)。有一些解决方案:
- 使用网络服务器托管您的代码(例如 nginx )。
- 使用不同的网络浏览器(例如 Firefox )。
- 完全禁用网络安全,请参阅this answer .
关于由于错误,Javascript 导入模块到 index.html 未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52343339/