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

构建后,浏览器不执行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
相关推荐
Ares-Wang4 分钟前
flask》》Blueprint 蓝图
后端·python·flask
iReachers12 分钟前
HTML打包EXE工具四种弹窗方式图文详解 - 单窗口/新窗口/标签页/浏览器打开
前端·javascript·html·弹窗·html打包exe·html转程序
编程小风筝12 分钟前
就业信息推荐系统 Python+Django+Vue.js
vue.js·python·django
耗子君QAQ21 分钟前
🔧 Rattail | 面向 Vite+ 和 AI Agent 的前端工具链
前端·javascript·vue.js
萑澈9 小时前
Windows 7 运行 Electron 安装包报“不是有效的 Win32 应用程序”怎么办
javascript·windows·electron
W.A委员会9 小时前
JS原型链详解
开发语言·javascript·原型模式
她说彩礼65万10 小时前
C# 实现简单的日志打印
开发语言·javascript·c#
一只蝉nahc10 小时前
vue使用iframe内嵌unity模型,并且向模型传递信息,接受信息
前端·vue.js·unity
状元岐11 小时前
C#反射从入门到精通
java·javascript·算法
a11177612 小时前
Three.js 的前端 WebGL 页面合集(日本 开源项目)
前端·javascript·webgl