Next.js v13 Docker构建不识别路径别名,但本地运行正常
问题描述
原本Docker构建正常,使用路径别名(绝对路径)后,pnpm run build步骤报错module not found, can't resolve 'ComponentName',本地运行完全正常。
相关配置及信息
tsconfig.json
{ "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [{"name": "next"}], "baseUrl": ".", "paths": {"~/*": ["./src/*"]} }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"] }
报错文件(src/app/layout.tsx)
import { Providers } from './providers'; import NavBar from '~/components/NavBar'; import { css } from '~/styles/css'; import './global.css'; export const metadata = { title: 'p-stack-fs', description: 'A boilerplate for TypeScript, Next.js, and PostgreSQL', }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <body> <Providers> <div className={css({ minH: '100vh' })}> <NavBar /> {children} </div> </Providers> </body> </html> ); }
错误信息
> [builder 6/6] RUN pnpm run build: #25 0.534 #25 0.534 > p-stack-fs@0.1.0 build /app #25 0.534 > next build #25 0.534 #25 0.940 - warn You have enabled experimental feature (instrumentationHook) in next.config.js. #25 0.941 - warn Experimental features are not covered by semver, and may cause unexpected or broken application behavior. Use at your own risk. #25 0.941 #25 1.010 - info Creating an optimized production build... #25 10.94 Failed to compile. #25 10.94 #25 10.95 ./src/app/layout.tsx #25 10.95 Module not found: Can't resolve '~/components/NavBar' #25 10.95 #25 10.95 ./src/app/layout.tsx #25 10.95 Module not found: Can't resolve '~/styles/css' #25 10.95 #25 10.95 > Build failed because of webpack errors #25 11.09 ELIFECYCLE Command failed with exit code 1. ------ executor failed running [/bin/sh -c pnpm run build]: exit code: 1
文件结构

Dockerfile
ARG ALPINE_VERSION=3.17 FROM node:20-alpine AS base # Install dependencies only when needed FROM base AS deps RUN apk add --no-cache libc6-compat WORKDIR /app COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./ COPY panda.config.ts ./ RUN npm i -g pnpm && pnpm i --prod --frozen-lockfile # Rebuild the source code only when needed FROM base AS builder WORKDIR /app COPY --from=deps /app/node_modules ./node_modules COPY . . RUN ["chmod", "+x", "./docker-entrypoint.sh"] ENV NEXT_TELEMETRY_DISABLED 1 RUN npm i -g pnpm RUN pnpm run build # Production image, copy all the files and run next FROM alpine:${ALPINE_VERSION} AS runner WORKDIR /app ENV NEXT_TELEMETRY_DISABLED 1 RUN apk add --no-cache --update nodejs RUN apk update && apk add --no-cache ca-certificates && update-ca-certificates RUN wget https://github.com/pthieu/go-aws-get-parameter/raw/master/ssm_get_parameter RUN ["chmod", "+x", "./ssm_get_parameter"] RUN addgroup --system --gid 1001 nodejs RUN adduser --system --uid 1001 nextjs COPY --from=builder /app/.next/standalone ./ COPY --from=builder /app/public ./public COPY --from=builder /app/.next/static ./.next/static COPY --from=builder --chown=nextjs:nodejs /app/docker-entrypoint.sh ./ USER nextjs EXPOSE 80 ENV PORT 80 ENTRYPOINT [ "sh", "docker-entrypoint.sh" ] CMD ["node", "server.js"]
解决方法
Next.js在Docker构建时无法识别tsconfig.json中的路径别名,需通过以下步骤修复:
- 同步配置next.config.js
创建或修改next.config.js,添加webpack别名解析规则:
const path = require('path'); /** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config) => { config.resolve.alias['~'] = path.resolve(__dirname, 'src'); return config; }, experimental: { instrumentationHook: true, // 保留原有实验特性配置 }, }; module.exports = nextConfig;
- 调整依赖安装命令
deps阶段使用--prod会跳过构建必需的开发依赖,修改为:
RUN npm i -g pnpm && pnpm i --frozen-lockfile
检查文件复制规则
确保.dockerignore没有排除tsconfig.json和next.config.js,Dockerfile中COPY . .已完整复制源码文件,无需额外调整。清理Docker缓存重试
执行以下命令清理缓存后重新构建:
docker system prune -af docker build .
按以上步骤调整后,路径别名即可在Docker构建中正常解析。
内容的提问来源于stack exchange,提问作者PGT
相关产品推荐
相关产品推荐

