flask+Vue(Vite)部署js文件不能被正确解析解决方案

1,154 阅读1分钟

构建后,浏览器不执行js文件,触发错误Strict MIME type checking is enforced for module scripts per HTML spec.Expected a JavaScript module script but the server responded with a MIME type of "text/plain".

问题原因

构建后,因为生产环境index.html​文件中<script>​标签使用了type="module"​,而服务器对于js文件的类型返回的是text/plain​,类型不一致,其详细解释可见.mjs 与 .js

解决方案一

手动修改index.562b9b5a.js​文件后缀为.mjs​,并将其对应的文件引用中文件名做相应更改(可能不止限于index.html​文件中)

缺点:麻烦,容易引起其他错误

解决方案二

配置Vite构建时不使用import​,如设置build.target​为edge15​,详细信息见Vite文档

缺点:强行降低版本可能导致构建失败

解决方案三(推荐)

对js文件更改响应头,在flask中插入代码

#更改js文件的返回头
@app.after_request
def changeHeader(response):
    disposition = response.get_wsgi_headers('environ').get(
        'Content-Disposition')  or ''#获取返回头文件名描述,如'inline; filename=index.562b9b5a.js'
    if disposition.rfind('.js') == len(disposition) - 3:
        response.mimetype = 'application/javascript'
    return response

该段代码使用了flask.responseFlask.after_request