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

Next 14国际化路由中静态资源无法加载,求正确引用方式

Next 14 国际化动态路由下静态资源正确引用方案

在app/[lang]这类动态路由目录下引用public文件夹的静态资源,核心规则是根相对路径直接访问,但加载失败通常是Image组件配置或路径细节问题,以下是具体解决方法:

一、图片资源(next/image)的正确用法

1. 配置Image域名(推荐)

App Router下使用next/image需要允许对应域名,在app/[lang]/layout.js中添加配置:

import { Image } from 'next/image'

export default function RootLayout({ children, params }) {
  return (
    <html lang={params.lang}>
      <body>{children}</body>
    </html>
  )
}

// 配置允许的图片域名,本地开发加localhost,生产环境替换为你的域名
export const config = {
  images: {
    domains: ['localhost', 'your-production-domain.com'],
  },
}

之后在page.js中正常用根路径引用:

import Image from 'next/image'
import styles from './page.module.css'

export default function Home({ params }) {
  return (
    <div>
      <Image
        src="/logo.svg"
        alt="Vercel Logo"
        className={styles.brandLogo}
        width={100}
        height={24}
        priority
      />
    </div>
  )
}

2. 跳过图片优化(快速解决)

如果不需要Next.js的图片优化功能,直接给Image组件加unoptimized属性:

<Image
  src="/logo.svg"
  alt="Vercel Logo"
  className={styles.brandLogo}
  width={100}
  height={24}
  priority
  unoptimized
/>

二、字体资源的引用方式

在global.css中引用public/fonts下的字体文件时,同样使用根相对路径:

@font-face {
  font-family: 'CustomFont';
  src: url('/fonts/your-font-file.woff2') format('woff2');
  font-weight: 400;
  font-style: normal;
  font-display: swap;
}

三、排查加载失败的常见原因

  • 确认public文件夹位置:必须和app文件夹同级,不能放在app/[lang]目录内。
  • 检查路径大小写:Linux/macOS环境下文件名区分大小写,确保代码里的路径和实际文件名完全一致。
  • 检查basePath配置:如果next.config.js中设置了basePath,需要把basePath加到资源路径前,比如basePath: '/my-app',则图片路径应为/my-app/logo.svg。

内容的提问来源于stack exchange,提问作者Nana Ampaw Boateng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 01:27:40