如何在Azure静态Web应用部署带basePath的Next.js SSG应用
解决Next.js配置basePath后部署到Azure静态Web应用的路径适配问题
1. 确认Next.js导出配置正确性
- 确保
next.config.mjs里的basePath、output及webpack配置无误:
/** @type {import('next').NextConfig} */ const nextConfig = { basePath: '/app1', output: 'export', webpack: (config) => { // SVG处理规则 config.module.rules.push({ test: /\.svg$/i, issuer: /\.[jt]sx?$/, use: ['@svgr/webpack'], }); // 模块联邦配置 // 此处填入你的联邦代码 return config; }, }; export default nextConfig;
- 本地执行
npm run build后,检查.next/export/app1目录,确认所有静态资源路径均带有/app1/前缀。
2. 调整Azure静态Web应用部署YAML
- 修改部署用YAML文件(如
azure-static-web-apps-xxx.yml),将output_location设为.next/export,确保Azure能识别包含app1子目录的导出根目录:
jobs: build_and_deploy_job: steps: - uses: actions/checkout@v3 with: submodules: true - name: Build And Deploy id: builddeploy uses: Azure/static-web-apps-deploy@v1 with: azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_XXX }} app_location: '/' # Next.js项目根目录 api_location: '' # 无API服务则留空 output_location: '.next/export' # 导出根目录,包含app1子文件夹
3. 配置staticwebapp.json路由规则
- 在项目根目录创建或修改
staticwebapp.json,添加路由重写和导航回退规则,适配Next.js客户端路由和basePath路径:
{ "routes": [ { "route": "/app1/*", "serve": "/app1/$1", "statusCode": 200 }, { "route": "/", "redirect": "/app1/", "statusCode": 302 } ], "navigationFallback": { "rewrite": "/app1/index.html" }, "globalHeaders": { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS" } }
- 注意:
navigationFallback必须指向/app1/index.html,否则客户端路由会出现404。
4. 模块联邦路径适配
- 模块联邦的远程入口URL需替换为部署后的生产路径:
// next.config.mjs中的模块联邦配置 new ModuleFederationPlugin({ name: 'app1', remotes: { mfe1: 'mfe1@https://xxx.staticapps.net/app1/remoteEntry.js', }, // 其他配置项 });
- 可通过环境变量区分开发/生产环境,避免硬编码:
const REMOTE_ENTRY = process.env.NODE_ENV === 'production' ? 'https://xxx.staticapps.net/app1/remoteEntry.js' : 'http://localhost:3001/app1/remoteEntry.js';
5. 部署后验证
- 访问
https://xxx.staticapps.net/app1/,打开浏览器开发者工具检查:- 静态资源(JS、CSS、SVG)的请求路径是否以
/app1/_next/开头且加载正常 - 模块联邦远程入口是否能正确获取,微应用渲染正常
- 客户端路由(如
/app1/about)是否能正常跳转,无404
- 静态资源(JS、CSS、SVG)的请求路径是否以
内容的提问来源于stack exchange,提问作者Kalyan
相关产品推荐
相关产品推荐

