Docker构建Next.js v13.5.4遇模块找不到错误求助
问题:Next.js 13.5.4在Jenkins Docker构建中出现模块找不到错误
我在将Next.js v13.5.4通过Docker构建时,在Jenkins流水线中遇到以下错误:
./app/page.tsx
Module not found: Can't resolve '@/components/ui/select'
本地开发、本地构建,以及直接用Dockerfile构建镜像都能正常运行,但Jenkins流水线里构建就失败。我尝试参考相关议题,在next.config.js中配置了webpack别名,但问题仍未解决。
现有配置文件
next.config.js
const path = require('path') /** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config) => { config.resolve.alias['@'] = path.join(__dirname) return config; }, output: 'standalone', }; module.exports = nextConfig;
tsconfig.json
{ ... "baseUrl": ".", "paths": { "@/components/*": ["components/*"], "@/constants/*": ["constants/*"], "@/lib/*": ["lib/*"], "@/schema/*": ["schema/*"], "@/types/*": ["types/*"], } }
Dockerfile
FROM node:20-alpine WORKDIR /app COPY package.json yarn.lock ./ # Install yarn # RUN apk add yarn RUN npm install yarn@1.22.19 # Install dependencies RUN yarn install RUN yarn cache clean # Copy the application code COPY / ./ # Set environment variables ENV NODE_ENV=production ENV PORT=3000 ENV NEXT_PUBLIC_BACKEND_URL=ENDPOINT # Disable Next.js telemetry ENV NEXT_TELEMETRY_DISABLED=1 # Build the application RUN yarn build # Expose the port EXPOSE 3000 # Start the application CMD ["yarn", "start"]
可能的原因及解决方案
1. 修复webpack别名路径映射
Jenkins工作目录的__dirname指向可能和本地不一致,导致别名映射失效。修改next.config.js的webpack配置,明确映射每个路径,和tsconfig保持对齐:
webpack: (config) => { config.resolve.alias['@/components'] = path.resolve(__dirname, 'components'); config.resolve.alias['@/constants'] = path.resolve(__dirname, 'constants'); config.resolve.alias['@/lib'] = path.resolve(__dirname, 'lib'); config.resolve.alias['@/schema'] = path.resolve(__dirname, 'schema'); config.resolve.alias['@/types'] = path.resolve(__dirname, 'types'); return config; },
2. 检查Jenkins文件复制完整性
确认Jenkins流水线是否完整复制了项目文件,尤其是components/ui/select目录:
- 检查流水线的文件复制步骤,确保包含所有必要目录(比如用
cp -r ./*而非选择性复制) - 排查
.dockerignore或.gitignore是否意外排除了components目录,如有则移除对应规则
3. 强制清除依赖缓存
Jenkins可能使用了缓存的依赖包,导致别名解析相关依赖未正确安装。修改Dockerfile的依赖安装步骤:
RUN yarn cache clean --force RUN yarn install --frozen-lockfile
4. 用插件同步TypeScript路径映射
安装tsconfig-paths-webpack-plugin让webpack正确识别tsconfig中的路径配置:
- 安装开发依赖:
yarn add tsconfig-paths-webpack-plugin --dev
- 修改
next.config.js:
const path = require('path'); const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin'); const nextConfig = { webpack: (config) => { config.resolve.plugins.push(new TsconfigPathsPlugin({ configFile: path.resolve(__dirname, 'tsconfig.json') })); return config; }, output: 'standalone', }; module.exports = nextConfig;
5. 对齐Jenkins环境的Node/Yarn版本
确认Jenkins代理的Node版本(v20)和Yarn版本(1.22.19)与本地一致,可在流水线中添加版本检查步骤:
stage('Check Versions') { steps { sh 'node -v' sh 'yarn -v' } }
内容的提问来源于stack exchange,提问作者ChuChuwi
相关产品推荐
相关产品推荐

