Azure App Service部署Next.js应用时node_modules缺失问题求助
解决azd部署Next.js到Azure App Service时.next/standalone/node_modules缺失问题
问题根源
本地构建Next.js的standalone模式时,.next/standalone目录会自动生成包含生产依赖的node_modules,但通过azd+GitHub Actions部署后该目录缺失,导致Cannot find module 'next'错误。核心原因是部署流程未确保完整上传构建产物,或App Service自动构建覆盖了原有产物。
解决方案
1. 确保Next.js构建启用standalone模式
修改项目根目录package.json中的build命令,添加--standalone参数:
{ "scripts": { "build": "next build --standalone" } }
2. 配置azure.yaml显式指定构建流程
更新azure.yaml,添加build字段确保部署前完成依赖安装和构建:
# yaml-language-server: $schema=https://raw.githubusercontent.com/Azure/azure-dev/main/schemas/v1.0/azure.yaml.json name: webapp metadata: template: azd-init@1.14.0 services: webapp: project: . host: appservice language: ts dist: .next/standalone build: | npm install --production npm run build
3. 调整GitHub Actions工作流,添加预构建步骤
如果不想依赖azd自动构建,可在工作流中显式执行构建,确保产物完整:
- name: Checkout code uses: actions/checkout@v4 - name: Install azd uses: Azure/setup-azd@v2 - name: Log in with Azure Developer CLI (Federated Credentials) run: | azd auth login ` --client-id "${{ secrets.AZURE_CLIENT_ID }}" ` --federated-credential-provider "github" ` --tenant-id "${{ secrets.AZURE_TENANT_ID }}" shell: pwsh - name: Install production dependencies run: npm install --production - name: Build Next.js application run: npm run build - name: Provision Infrastructure run: azd provision --no-prompt - name: Deploy Application run: azd deploy --no-prompt
4. 禁用App Service的自动构建
在Azure Portal进入目标App Service,前往配置 > 应用设置,添加或修改SCM_DO_BUILD_DURING_DEPLOYMENT为false,避免App Service重新构建覆盖已上传的standalone产物。
验证方法
部署完成后,通过SCM连接(https://<your-app-name>.scm.azurewebsites.net/)查看site/wwwroot/.next/standalone目录,确认node_modules存在,随后重启App Service即可恢复正常运行。
内容的提问来源于stack exchange,提问作者rndm
相关产品推荐
相关产品推荐

