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

React中如何将JSON文件作为URL导入而非直接导入内容?

实现CRA中导入JSON获取URL而非直接导入内容

你可以通过两种方式实现需求,无需eject项目,下面分别说明:

方案一:直接将JSON放入public目录(无需修改配置)

把大体积JSON文件放到项目根目录的public文件夹下,之后直接通过相对根路径的URL来发起请求:

fetch('/large-data.json')
  .then(res => res.json())
  .then(data => {
    // 在这里处理加载后的JSON数据
  });

这种方式最简单,不需要修改任何构建配置,JSON文件会被直接复制到build产物的根目录,不会被打包进JS bundle。

方案二:用Craco修改Webpack配置,实现类似图片的导入方式

如果你希望保持和图片一致的import语法,可以通过Craco覆盖CRA的默认Webpack规则:

  1. 安装Craco依赖
npm install @craco/craco --save-dev
# 或者用yarn
yarn add @craco/craco --dev
  1. 在项目根目录创建craco.config.js,添加如下配置:
module.exports = {
  webpack: {
    configure: (webpackConfig) => {
      // 移除CRA默认的JSON解析规则
      webpackConfig.module.rules = webpackConfig.module.rules.filter(
        rule => !(rule.type === 'json' && rule.parser?.parse)
      );

      // 添加新规则,用file-loader处理JSON文件
      webpackConfig.module.rules.push({
        test: /\.json$/,
        exclude: /node_modules/, // 可选:排除node_modules中的JSON文件
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'static/media/[name].[hash:8].[ext]', // 和图片的输出路径/命名规则保持一致
            },
          },
        ],
      });

      return webpackConfig;
    },
  },
};
  1. 修改package.json中的启动/构建脚本,替换为Craco命令:
"scripts": {
  "start": "craco start",
  "build": "craco build",
  "test": "craco test"
}
  1. 现在就可以像导入图片一样导入JSON文件,得到的是文件URL:
import jsonUrl from './large-data.json';

fetch(jsonUrl)
  .then(res => res.json())
  .then(data => {
    // 处理加载后的JSON数据
  });

补充说明

如果需要区分处理不同的JSON文件(比如部分小JSON仍需直接导入内容),可以调整test规则,比如只匹配特定前缀的文件:

test: /large-.+\.json$/ // 仅处理以large-开头的JSON文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 17:02:45