浏览器控制台报错Failed to load module script:解决方法

错误

用nginx做vue3+vite2代理的时候出现了以下的报错

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

原因

经检查,出现这种状况是因为我的项目二级目录和nginx转发的目录不匹配。 在nginx配置中,我是这样写的

location /h5-page {
 try_files $uri $uri/ /jd-h5/index.html last;
}

而在vite配置中,我将base设置为h5-page;

export default defineConfig(({ mode }) => ({
 base: '/h5-page/',
}));

由于我转发的location和目录的base都设置为h5-page,但是我却实际上将打包好的文件放在了jd-h5这个目录中,这让nginx无法准确定位到文件因而产生了上述的报错;

解决方法

解决方法也很简单,将不匹配的部分修正即可,我将目录重命名为h5-page,然后修改nginx配置。

location /h5-page {
 try_files $uri $uri/ /h5-page/index.html last;
}

总结

用二级目录托管项目,如果不想造成混淆和报错的话,应当严格遵照 目录-转发地址-项目base 统一的写法。

作者:Xmo

%s 个评论

要回复文章请先登录注册