我正在尝试将模块导入到我的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>
Run Code Online (Sandbox Code Playgroud)
还有js:
export function addTextToBody(text) {
const div = document.createElement('div');
div.textContent = text;
document.body.appendChild(div);
}
Run Code Online (Sandbox Code Playgroud)
我收到这些错误:
未捕获的语法错误:意外的标记 { - 第 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>
Run Code Online (Sandbox Code Playgroud)
// module.js
export function addTextToBody(text) {
const div = document.createElement('div');
div.textContent = text;
document.body.appendChild(div);
}
Run Code Online (Sandbox Code Playgroud)
上面提供的代码适用于 Firefox,但不适用于 Chrome。看来您正在使用 Chrome(我认为从您的错误消息来看)。Chrome严格禁止访问具有该file://
协议的资源。有几种解决方案: