javascript - Flask:如何使用 ES6 模块?

标签 javascript python flask es6-modules

我有一个正在运行的 Flask 应用程序,我正在尝试重构它以使用 ES6 导入。我不需要它在旧浏览器上运行,而且 ES6 导入在现代浏览器中无需转换就可以工作,对吧?

我目前只是通过 Flask 的内置服务器运行它。生产应用程序是通过 gevent 提供的,但显然我还没有进行这些更改。

以下是我到目前为止尝试过的内容。我哪里出错了?

View .py

@app.route('/home')
def serve_home():
    return render_template('home.html')

格式化.js

export function formatNumber(...) {
  ...
}

尝试 1

主页.html

<script type="text/javascript" src="/static/js/main.js"></script>

主要.js

import {formatNumber} from "/static/js/formatting.js";

错误(main.js,第 1 行)

Uncaught SyntaxError: Unexpected token {

尝试 2

  • 将脚本类型更改为“模块”

主页.html

<script type="module" src="/static/js/main.js"></script>

错误(main.js,第 1 行)

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.

尝试 3

  • 将两个 Javascript 文件的扩展名从“js”更改为“mjs”

主页.html

<script type="module" src="/static/js/main.mjs"></script>

主要.mjs

import {formatNumber} from "/static/js/formatting.mjs";

错误(main.mjs,第 1 行)

Failed to load module script: The server responded with a non-JavaScript MIME type of "application/octet-stream". Strict MIME type checking is enforced for module scripts per HTML spec.

最佳答案

对于那些遇到错误的人:

The server responded with a non-JavaScript MIME type [...]

...您需要确认 python 正在返回您的 JS 文件的预期 mimetype。

>>> import mimetypes
>>> mimetypes.guess_type("notExists.js")
('text/javascript', None)

对于我自己,使用 Windows 平台从(例如 Flask 的开发服务器)托管 Web 服务器,我发现我需要更新注册表以将文件扩展名与 text/javascript 相关联。

例如,在注册表编辑器中:

  1. 在 HKEY_CLASSES_ROOT 下,找到 .js(如果使用 .mjs)
  2. 查看“内容类型”的值。它必须text/javascript,而不是text/plain,或application/octet-stream

关于javascript - Flask:如何使用 ES6 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56587108/

相关文章:

javascript - JS es2015 中未知的函数格式

javascript - 如何更改chartjs中的x轴线样式?

javascript - Google javascript API 库 - 日历 watch 通知

python - 在 Python 中返回数组中最大元素的索引

python-2.7 - python - Flask test_client() 没有使用 pytest 的 request.authorization

javascript - 如何使用 Lodash.js 删除数组项?

python - 在 python discordpy 中加载扩展

python - 如何在 Python 3 中将二进制转换为字节再转换为十六进制?

python - 为什么 Flask 自动调试在 ubuntu 中不起作用

routes - 在 Flask 中阻止特定路由上的引荐来源网址