GitHub Pages部署后页面空白,疑似TS未转译?求助排查
项目部署到GitHub Pages后网站空白,浏览器标签页能正常显示HTML的<title>内容,但页面无任何内容,控制台抛出如下错误:
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/octet-stream". Strict MIME type checking is enforced for module scripts per HTML spec.
错误来源显示为main.tsx:1,推测TS代码未被转译为JS,部署时执行的是npm run deploy命令。
相关配置文件
package.json
{ "name": "guess-the-wiki", "homepage": "https://djbalin.github.io/guess-the-wiki/", "private": true, "version": "0.1.0", "type": "module", "scripts": { "dev": "vite", "build": "tsc && vite build", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "preview": "vite preview", "test": "jest", "predeploy": "npm run build", "deploy": "gh-pages -d dist" }, "dependencies": { "axios": "^1.5.1", "react": "^18.2.0", "react-dom": "^18.2.0" }, "devDependencies": { "@babel/core": "^7.23.2", "@babel/preset-env": "^7.23.2", "@babel/preset-typescript": "^7.23.2", "@types/jest": "^29.5.5", "@types/react": "^18.2.15", "@types/react-dom": "^18.2.7", "@typescript-eslint/eslint-plugin": "^6.0.0", "@typescript-eslint/parser": "^6.0.0", "@vitejs/plugin-react": "^4.0.3", "autoprefixer": "^10.4.16", "babel-jest": "^29.7.0", "eslint": "^8.45.0", "eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-react-refresh": "^0.4.3", "jest": "^29.7.0", "postcss": "^8.4.31", "tailwindcss": "^3.3.3", "typescript": "^5.0.2", "vite": "^4.4.5", "vite-tsconfig-paths": "^4.2.1" } }
tsconfig.node.json
{ "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true }, "include": ["vite.config.ts"] }
vite.config.ts
import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; // import tsconfigPaths from "vite-tsconfig-paths"; // https://vitejs.dev/config/ export default defineConfig({ base: "/guess-the-wiki/", plugins: [react()], });
根据错误信息和配置,核心问题是GitHub Pages返回的TSX文件MIME类型不符合要求,导致浏览器无法识别为JS模块。以下是具体排查和解决步骤:
检查构建产物是否正确
执行npm run build后,查看项目根目录的dist文件夹,确认里面是编译后的.js/.jsx文件,而非原.tsx源码。如果dist里仍有.tsx文件,说明Vite构建未完成转译。补充项目级TypeScript配置
当前仅提供了tsconfig.node.json(用于配置Vite自身),但项目源码需要根目录的tsconfig.json来指导编译。创建或完善该文件,参考配置如下:{ "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", "skipLibCheck": true, "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx" }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] }缺少这个配置会导致Vite无法正确处理TSX文件的转译流程。
验证部署分支内容
登录GitHub查看项目的gh-pages分支,确认上传的是dist目录的编译产物,而非项目源码。如果分支里有.tsx文件,可删除node_modules/.cache/gh-pages缓存后重新执行npm run deploy。检查构建过程是否报错
重新执行npm run build,观察终端输出是否有TypeScript语法或类型错误。这类错误会中断构建,导致dist目录保留未编译的旧文件。
内容的提问来源于stack exchange,提问作者Jan Balin

