使用Vite搭建React项目启动报错:MIME类型不匹配求助
解决Vite React项目启动时MIME类型错误问题
问题描述
使用Vite搭建React项目,无论是通过局域网IP还是localhost启动,均出现以下报错:
ERROR: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html"
关键代码
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Asset Scanner</title> <script src="https://cdn.socket.io/4.2.0/socket.io.min.js" integrity="sha384-PiBR5S00EtOj2Lto9Uu81cmoyZqR57XcOna1oAuVuIEjzj0wpqDVfD0JA9eXlRsj" crossorigin="anonymous" ></script> </head> <body> <div id="root"></div> <div id="modals"></div> <script type="module" src="/src/main.jsx"></script> </body> </html>
src/main.jsx
import React from 'react' import ReactDOM from 'react-dom' import App from '@@/App' import { loadCSSVariables } from './common/utils/cssVariables' loadCSSVariables().then(() => { ReactDOM.render(<App />, document.getElementById('root')) })
问题分析与解决步骤
1. 修复路径别名配置
main.jsx中使用的@@/App路径别名Vite默认不识别,当Vite无法解析该路径时,会返回404错误页面(text/html类型),进而触发MIME类型报错。
在项目根目录的vite.config.js中添加别名映射配置:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import path from 'path' export default defineConfig({ plugins: [react()], resolve: { alias: { '@@': path.resolve(__dirname, './src') // 将@@指向项目src目录 } } })
2. 验证文件路径正确性
确认src/App.jsx文件存在,且路径与别名映射规则匹配。如果App组件位于子目录中,需调整导入路径(例如@@/components/App)或修改别名映射范围。
3. 清理缓存并重启服务
- 终止当前Vite服务,重新执行
npm run dev启动项目 - 清除浏览器缓存(快捷键:Ctrl+Shift+R / Cmd+Shift+R),避免缓存旧的错误响应
4. 检查依赖版本兼容性
确保@vitejs/plugin-react与Vite版本兼容,执行以下命令更新依赖:
npm update vite @vitejs/plugin-react
内容的提问来源于stack exchange,提问作者Veera Silamban
相关产品推荐
相关产品推荐

