Next.js项目部署至Netlify/Heroku时出现导入路径错误求助
Next.js部署到Heroku/Netlify时出现导入路径大小写不匹配错误
问题现象
将Next.js项目部署到Heroku或Netlify时,构建过程抛出模块找不到的类型错误,本地开发环境运行完全正常。
错误日志
./pages/_app.tsx:7:27 6:31:19 PM: Type error: Cannot find module '../styles/Body' or its corresponding type declarations. 6:31:19 PM: 5 | import { Box } from "@mui/material"; 6:31:19 PM: 6 | import { useState } from "react"; 6:31:19 PM: > 7 | import pageContainer from "../styles/Body"; 6:31:19 PM: | ^ 6:31:19 PM: 8 | 6:31:19 PM: 9 | function MyApp({ Component, pageProps }: AppProps) { 6:31:19 PM: 10 | const [darkMode, setDarkMode] = useState(false); 6:31:19 PM: > Build error occurred 6:31:19 PM: Error: Call retries were exceeded 6:31:19 PM: at ChildProcessWorker.initialize (/opt/build/repo/node_modules/next/dist/compiled/jest-worker/index.js:1:11661) 6:31:19 PM: at ChildProcessWorker._onExit (/opt/build/repo/node_modules/next/dist/compiled/jest-worker/index.js:1:12599) 6:31:19 PM: at ChildProcess.emit (node:events:513:28) 6:31:19 PM: at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12) { 6:31:19 PM: type: 'WorkerError' 6:31:19 PM: } 6:31:19 PM: 6:31:19 PM: ──────────────────────────────────────────────────────────────── 6:31:19 PM: "build.command" failed 6:31:19 PM: ──────────────────────────────────────────────────────────────── 6:31:19 PM: 6:31:19 PM: Error message 6:31:19 PM: Command failed with exit code 1: CI= npm run build
相关代码
pages/_app.tsx
import "../styles/globals.css"; import pageContainer from "../styles/Body"; function MyApp({ Component, pageProps }: AppProps) { const [darkMode, setDarkMode] = useState(false); return ( <> <Box sx={pageContainer(darkMode)}> <NavBar darkMode={darkMode} onSetDarkMode={setDarkMode} /> <Component darkMode={darkMode} {...pageProps} /> </Box> </> ); } export default MyApp;
styles/Body.tsx
const container = { direction: "rtl", padding: "1rem 0 1.6rem", backgroundColor: "#f5f5f5", }; const nightMode = { backgroundColor: "#1E272E", }; export default function pageContainer(isNight: boolean): object[] | object { return isNight ? [container, nightMode] : container; }
问题原因与解决方案
原因
本地开发环境(如Windows/macOS)的文件系统默认大小写不敏感,因此即使实际文件名为body.tsx,导入../styles/Body也能正常识别;但部署平台的服务器基于Linux系统,文件系统大小写敏感,而提交到GitHub的文件名仍为body.tsx,与导入路径的Body大小写不一致,导致构建时无法找到模块。
解决步骤
- 在本地终端执行大小写敏感的重命名命令(避免系统自动忽略大小写差异):
git mv styles/body.tsx styles/Body.tsx - 提交并推送文件名变更到GitHub:
git add styles/Body.tsx git commit -m "fix: 修正文件名大小写以匹配导入路径" git push - 重新触发Heroku或Netlify的构建流程即可解决问题。
内容的提问来源于stack exchange,提问作者xibymepy
相关产品推荐
相关产品推荐

