Next.js14.1.1导出静态文件时设置相对路径的方法
解决Next.js 14.1.1导出静态HTML时资源相对路径问题
Next.js的assetPrefix确实不支持以./开头的相对路径配置,不过可以通过静态导出+构建后脚本替换的方式解决,步骤如下:
- 配置静态导出
在next.config.mjs中添加静态导出相关配置,确保生成纯静态文件:
/** @type {import('next').NextConfig} */ const nextConfig = { output: 'export', // 指定导出为静态HTML/CSS/JS trailingSlash: true, // 为每个页面生成index.html,适配相对路径访问 } export default nextConfig;
- 执行导出命令
运行构建命令生成静态文件,产物默认在out目录:
npm run build
- 编写路径替换脚本
创建一个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);
- 自动执行替换脚本
在package.json的scripts中添加postbuild命令,让构建完成后自动运行替换脚本:
"scripts": { "build": "next build", "postbuild": "node fix-paths.js" }
之后再执行npm run build,生成的out目录中的HTML文件就会使用相对路径引用静态资源了,直接将整个out目录部署到任意静态服务器即可。
内容的提问来源于stack exchange,提问作者SirSaleh
相关产品推荐
相关产品推荐

