React中动态更新require路径加载本地JSON文件问题求助
Fixing Dynamic Require for Local JSON Files in React
Hey there! That error you're hitting happens because bundlers like Webpack need to know all your dependencies at build time. When you dynamically stitch together a path like ./json/${e.target.value}.json, Webpack can't predict which files you'll need ahead of time—so it throws that "not declared as a dependency" error. Let's fix this while sticking strictly to using require.
The Solution: Use require.context
We can leverage Webpack's require.context to explicitly tell the bundler to include all JSON files in your ./json directory upfront. This way, when you dynamically load a file later, it's already part of the bundle and ready to go.
Here's your adjusted code with this approach:
import React, { Component } from 'react'; import { render } from 'react-dom'; // Create a context to bundle all JSON files in the ./json directory const jsonFilesContext = require.context('./json', false, /\.json$/); class App extends Component { state = { user: {}, // Start with empty object to avoid initial render errors userSelected: null, }; handleChange = (e) => { const selectedFileName = e.target.value; try { // Use the preconfigured context to dynamically load the JSON file const userData = jsonFilesContext(`./${selectedFileName}.json`); this.setState({ user: userData, userSelected: selectedFileName }); } catch (err) { console.log(`Failed to load file: ${selectedFileName}.json`, err.message); // Reset state if invalid filename is entered this.setState({ user: {}, userSelected: null }); } }; render() { const { user } = this.state; return ( <div> <input value={this.state.userSelected || ''} onChange={this.handleChange} placeholder="Enter filename (without .json)" /> {/* Add conditional checks to prevent errors when user data is missing */} {user.name && <h1>{user.name}</h1>} {user.age && <p>You are {user.age} years old</p>} {!user.name && <p>Enter a valid filename to see user details</p>} </div> ); } } render(<App />, document.getElementById('root'));
Key Changes Breakdown:
require.context: This line tells Webpack to bundle every.jsonfile in the./jsonfolder. The parameters mean:./json: The directory to scan for filesfalse: Don't recursively check subdirectories/\.json$/: Regex pattern to match only JSON files
- Dynamic Loading: Instead of building a string path for
require, we use the preconfigured context to fetch the file. This works because Webpack already knows about all these files from the context declaration. - Error & Edge Case Handling: We added input placeholder text, conditional rendering, and state resets to avoid React errors when the
userobject is empty (like on initial load or if an invalid filename is entered).
Quick Notes:
- Ensure your JSON files are stored in a
jsondirectory relative to this component file (adjust the path inrequire.contextif your folder structure is different). - When typing in the input, users should enter the filename without the
.jsonextension—we automatically add that in the code.
内容的提问来源于stack exchange,提问作者Andruraj
相关产品推荐
相关产品推荐

