首页 > 解决方案 > 加载模块脚本失败:服务器以非 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 类型检查。

为什么?我可以修吗?如何?

标签: javascript

解决方案


PHP 的简单内置服务器没有为.mjs文件注册 MIME 类型。它不是一个常见的扩展,通常仅用于 Node.js 中的 ES6 模块(并且由于 中的type 选项package.json而不再需要)。

重命名文件以再次具有.js扩展名,您的 HTTP 服务器将为它发送正确的 Content-Type。


推荐阅读