我有一个正在运行的 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
相关联。
例如,在注册表编辑器中:
- 在 HKEY_CLASSES_ROOT 下,找到
.js
(如果使用.mjs
) - 查看“内容类型”的值。它必须说
text/javascript
,而不是text/plain
,或application/octet-stream
等
关于javascript - Flask:如何使用 ES6 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56587108/