javascript - 加载模块脚本失败:服务器以非 JavaScript MIME 类型“”响应
问题描述
我有这个带有模块的html页面......
<html>
<body>
<hello-world color="blue" />
<hello-world color="red" />
<hello-world />
<script type="module">
import { HelloWorld } from './HelloWorld.js'
window.customElements.define('hello-world', HelloWorld)
</script>
</body>
</html>
...模块内容是...
export class HelloWorld extends HTMLElement {
get color () {
return this.getAttribute('color') || 'gray'
}
set color (value) {
this.setAttribute('color', value)
}
connectedCallback() {
window.requestAnimationFrame(() => {
const div = document.createElement('div')
div.textContent = 'Hello World!!!'
div.style.color = this.color
this.appendChild(div)
});
}
}
我使用 PHP 服务器运行php -S localhost:8888 -t .
并且一切正常:
相反,...如果我在./main.mjs
文件中移动模块的内容...
import { HelloWorld } from './HelloWorld.js'
window.customElements.define('hello-world', HelloWorld)
...更改...中的html部分
<html>
<body>
<hello-world color="blue" />
<hello-world color="red" />
<hello-world />
<script type="module" src="main.mjs"></script>
</body>
</html>
...我收到以下错误:
加载模块脚本失败:服务器以非 JavaScript MIME 类型“”响应。根据 HTML 规范对模块脚本强制执行严格的 MIME 类型检查。
为什么?我可以修吗?如何?
解决方案
PHP 的简单内置服务器没有为.mjs
文件注册 MIME 类型。它不是一个常见的扩展,通常仅用于 Node.js 中的 ES6 模块(并且由于 中的type 选项package.json
而不再需要)。
重命名文件以再次具有.js
扩展名,您的 HTTP 服务器将为它发送正确的 Content-Type。
推荐阅读
- django - django.db.utils.IntegrityError: UNIQUE constraint failed: authentication_user.email
- docker - docker:在 gitlab-ci 中找不到命令
- python - Python中按键分组的字典列表
- sql - 有什么方法可以改进我的 PostgreSQL 上的这个查询吗?
- django - 在调用部署之前查找静态文件是否存在 - Django
- python - 覆盖内置函数并将其转移到外部 python 脚本调用的方法(即 os.system("Script2.py"))
- python - Tkinter CheckButton 状态没有改变
- javascript - 展开选择以包括 AnchorNode 和 FocusNode 的所有文本
- javascript - 问一下jquery函数操作
- python - Python 命令历史记录在 PowerShell、Windows 中不起作用