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

在Create React App中批量导入文件夹内所有JSON文件的方法咨询

Bulk Import JSON Files Instead of Individual Imports

Hey there! Totally get why manually importing each JSON file one by one feels like a chore—let’s go through practical, scalable solutions based on your project’s build tool or environment:

1. For Webpack-based Projects (e.g., Create React App, Vue CLI)

Use Webpack’s built-in require.context to dynamically import all matching files:

// Create a helper function to import and organize JSON files
const importAllJson = (requireContext) => {
  const jsonCollection = {};
  requireContext.keys().forEach((filePath) => {
    // Extract the filename (without path and .json extension) as the key
    const fileName = filePath.replace(/^\.\/(.*)\.json$/, '$1');
    jsonCollection[fileName] = requireContext(filePath);
  });
  return jsonCollection;
};

// Target the "../Assets" folder, no subfolders, only .json files
const allAssetsJson = importAllJson(require.context('../Assets', false, /\.json$/));

// Export all files as a single object, or destructure for individual exports
export default allAssetsJson;
// Optional: Export specific files if you still need named exports
export const TXT1 = allAssetsJson.TTCS1;
export const TXT2 = allAssetsJson.TTCS2;

How it works:

  • require.context('../Assets', false, /\.json$/) creates a context that includes all .json files in the ../Assets folder (change the second argument to true if you need to include subfolders recursively).
  • The helper function maps each file to a key-value pair, using the clean filename (like TTCS1) as the key for easy access.

2. For Vite-based Projects

Vite provides import.meta.glob for modern, straightforward dynamic imports:

// Sync import (eager: true loads files immediately)
const rawJsonFiles = import.meta.glob('../Assets/*.json', { eager: true });

// Format the imported files to use filenames as keys
const formattedJsonFiles = {};
for (const [path, module] of Object.entries(rawJsonFiles)) {
  // Extract the filename from the full path
  const fileName = path.split('/').pop().replace('.json', '');
  formattedJsonFiles[fileName] = module.default;
}

// Export the collection or individual files
export default formattedJsonFiles;
export const TXT1 = formattedJsonFiles.TTCS1;
export const TXT2 = formattedJsonFiles.TTCS2;

Notes:

  • If you don’t need synchronous loading (e.g., for lazy loading), remove the eager: true option and use async/await to load files when needed.

3. For Node.js Environments (Backend/Scripts)

Use Node.js’s native fs module to read the directory and parse JSON files directly:

const fs = require('fs').promises;
const path = require('path');

async function bulkImportJson(dirPath) {
  const jsonFiles = {};
  const files = await fs.readdir(dirPath);

  for (const file of files) {
    if (path.extname(file) === '.json') {
      const fullPath = path.join(dirPath, file);
      const fileContent = await fs.readFile(fullPath, 'utf8');
      const fileName = path.basename(file, '.json');
      jsonFiles[fileName] = JSON.parse(fileContent);
    }
  }

  return jsonFiles;
}

// Usage example
bulkImportJson('../Assets')
  .then((files) => {
    console.log(files.TTCS1); // Access individual JSON content
  })
  .catch((err) => console.error('Error importing JSON files:', err));

Key Advantage of These Approaches

All these methods automatically include new .json files added to the ../Assets folder—no need to update your import statements every time you add a file, making your code way more maintainable.

内容的提问来源于stack exchange,提问作者Jaypal Thakur

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 10:37:31