You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js14.1.1导出静态文件时设置相对路径的方法

解决Next.js 14.1.1导出静态HTML时资源相对路径问题

Next.js的assetPrefix确实不支持以./开头的相对路径配置,不过可以通过静态导出+构建后脚本替换的方式解决,步骤如下:

  1. 配置静态导出
    在next.config.mjs中添加静态导出相关配置,确保生成纯静态文件:
/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'export', // 指定导出为静态HTML/CSS/JS
  trailingSlash: true, // 为每个页面生成index.html,适配相对路径访问
}

export default nextConfig;
  1. 执行导出命令
    运行构建命令生成静态文件,产物默认在out目录:
npm run build
  1. 编写路径替换脚本
    创建一个fix-paths.js文件,用来批量替换out目录下所有HTML文件中的绝对资源路径:
const fs = require('fs');
const path = require('path');

const outDir = path.join(__dirname, 'out');

// 替换单个HTML文件中的路径
function fixFilePaths(filePath) {
  const content = fs.readFileSync(filePath, 'utf8');
  // 将所有/_next/开头的路径替换为./_next/
  const updatedContent = content.replace(/\/_next\//g, './_next/');
  fs.writeFileSync(filePath, updatedContent);
}

// 遍历out目录处理所有HTML文件
function traverseDirectory(dir) {
  const files = fs.readdirSync(dir);
  files.forEach(file => {
    const fullPath = path.join(dir, file);
    const stats = fs.statSync(fullPath);
    if (stats.isDirectory()) {
      traverseDirectory(fullPath);
    } else if (path.extname(fullPath) === '.html') {
      fixFilePaths(fullPath);
    }
  });
}

traverseDirectory(outDir);
  1. 自动执行替换脚本
    在package.json的scripts中添加postbuild命令,让构建完成后自动运行替换脚本:
"scripts": {
  "build": "next build",
  "postbuild": "node fix-paths.js"
}

之后再执行npm run build,生成的out目录中的HTML文件就会使用相对路径引用静态资源了,直接将整个out目录部署到任意静态服务器即可。

内容的提问来源于stack exchange,提问作者SirSaleh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 04:55:04