如何在 python http.server 上使用 ES6 模块?

The*_*ing 4 javascript python server

我正在实例化一个模块,如下所示index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Hello Module</title>
  </head>
  <body>
    <script type="module" src="./index.js"></script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

index.js是空的。

当我通过(Python 3.8.5)提供此服务时py -3 -m http.server,我收到 Chrome 错误:

Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec.
Run Code Online (Sandbox Code Playgroud)

我已经读过这个错误的含义。我不知道如何配置 http.server,因为迄今为止它对我来说一直是一个黑匣子。我是否已经过了 Python 默认(?)服务器有用的阶段?

AKX*_*AKX 11

JavaScript 应该与 content-type 一起提供text/javascript

默认http.server.SimpleHTTPRequestHandler处理程序.js可能没有(因为可以从 Windows 注册表读取映射)具有文件类型扩展名的映射,或者它可能是错误的(从 中可以明显看出text/plain)。

您需要编写自己的简短脚本来修补扩展.js,并使用它来代替python -m http.server,例如:

import http.server

HandlerClass = http.server.SimpleHTTPRequestHandler

# Patch in the correct extensions
HandlerClass.extensions_map['.js'] = 'text/javascript'
HandlerClass.extensions_map['.mjs'] = 'text/javascript'

# Run the server (like `python -m http.server` does)
http.server.test(HandlerClass, port=8000)
Run Code Online (Sandbox Code Playgroud)