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

使用i18next执行run build时出现绝对URL错误,如何解决?

解决next-i18next执行npm run build时的"Only absolute URLs are supported"错误

错误信息

执行构建命令时出现以下错误:

i18next::backendConnector: loading namespace translation for language en failed TypeError: Only absolute URLs are supported

我的配置文件

next-i18next.config.js代码如下:

const path = require("path");

/** @type import("next").I18NConfig */
const i18n = {
    defaultLocale: 'en',
    locales: ['en', 'fr'],
    localeDetection: false // disable automatic redirection on the user's preferred locale
};

/** @type import("next-i18next").UserConfig */
const next18nextConfig = {
    i18n,
    fallbackLng: 'en',
    keySeparator: ".",
    nsSeparator: ":",
    localePath: path.resolve("./public/locales"),
    ns: ['common']
    // reloadOnPrerender: process.env.NODE_ENV === "development"
};

翻译文件路径

翻译文件存放路径:

/public/locales/[folder]/[file_name.json]

示例:

/public/locales/en/common.json

我尝试了官方示例代码,但仍出现相同错误,以下是可行的解决方法:


解决方法

  • 版本兼容性检查:确保next-i18next版本与Next.js版本匹配,比如Next.js 13+需要next-i18next v13及以上版本,版本不兼容会引发资源加载类错误。

  • 区分环境设置localePath:服务器端构建需要绝对路径,客户端需要相对URL路径,修改配置为:

    localePath: typeof window === 'undefined' ? path.resolve('./public/locales') : '/locales',
    
  • 启用开发环境的reloadOnPrerender:取消注释配置中该行,确保开发环境下翻译文件可重新加载,生产环境自动禁用:

    reloadOnPrerender: process.env.NODE_ENV === "development"
    
  • 检查翻译文件完整性:确认所有locale目录下的common.json存在且语法正确(无逗号遗漏、引号不匹配等问题),文件损坏可能触发误导性的URL错误提示。

  • 同步basePath配置:如果Next.js项目设置了basePath,需在next18nextConfig中添加对应basePath字段,保证翻译文件加载路径正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 03:35:22