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

Next.js构建阶段导入JSON文件失败,如何解决?

解决Next.js构建时JSON导入读取失败的问题

问题诊断

构建时出现的TypeError: Cannot read properties of undefined (reading 'home'),核心原因是data[language]返回了undefined——要么是传入的language值不在JSON的键列表中,要么是生产构建环节中JSON模块未被正确解析加载。

解决方案

1. 增加参数合法性校验

先确保传入的语言参数是JSON中已定义的键,避免访问不存在的属性:

import data from './data.json';

export type HomeLabels = typeof data.in.home;
export type SupportedLanguage = keyof typeof data;

export function getHomeLabels(language: string): HomeLabels {
  // 校验语言是否支持,不支持则返回默认语言的配置
  const validLanguage = Object.keys(data).includes(language) ? language as SupportedLanguage : "in";
  return data[validLanguage].home;
}

2. 替换导入方式为require

若Next.js构建时的模块解析存在问题,改用require导入JSON可规避该类问题:

const data = require('./data.json');

export type HomeLabels = typeof data.in.home;
export type SupportedLanguage = keyof typeof data;

export function getHomeLabels(language: string): HomeLabels {
  const validLanguage = Object.keys(data).includes(language) ? language as SupportedLanguage : "in";
  return data[validLanguage].home;
}

3. 确保Next.js配置正确处理JSON

检查next.config.js是否存在影响JSON解析的自定义配置,默认情况下Next.js支持JSON导入,若有自定义webpack规则,需保留JSON处理逻辑:

// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config) => {
    // 保留默认JSON处理规则
    config.module.rules.push({
      test: /\.json$/,
      type: 'json',
    });
    return config;
  },
};

module.exports = nextConfig;

4. 验证构建时的路径正确性

开发环境与生产构建的路径解析可能存在差异,可尝试使用绝对路径导入:

// 在tsconfig.json中配置baseUrl为项目根目录后,使用绝对路径
import data from 'config/labels/data.json';

同时在tsconfig.json中添加配置:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "config/*": ["config/*"]
    }
  }
}

内容的提问来源于stack exchange,提问作者Wilson de Freitas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:15:36