在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.jsonfiles in the../Assetsfolder (change the second argument totrueif 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: trueoption 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
相关产品推荐
相关产品推荐

