如何使用file-loader与Webpack加载React应用中的大JSON文件?
Hey there! I get why this is confusing—you turned to file-loader for that massive 144MB JSON file, but instead of getting the actual data, you're just getting a file path string. Let's break down why this happens and how to fix it.
Why you're seeing a file path instead of JSON
First, let's clarify what file-loader does: its whole job is to take static files (like images, fonts, or in your case, huge JSON files), copy them to your Webpack output directory, and then return the relative path/URL to that file. It doesn't parse or load the file's content into your bundle—this is intentional, because shoving a 144MB JSON into your JS bundle would make it impossibly large and slow to load.
Solution 1: Load the JSON at runtime (recommended for large files)
Since your JSON is so big, the best practice is to keep it as a separate file and fetch it when your app needs it. Here's how to do that:
- Keep your
file-loaderconfig for this JSON file (so Webpack copies it to your output folder). - Instead of trying to
requirethe data directly, use the path to fetch the file:
// Get the path to the output JSON file const jsonFilePath = require('../../data/origin_destination.json'); // Fetch and parse the JSON at runtime fetch(jsonFilePath) .then(response => { if (!response.ok) throw new Error('Failed to load JSON'); return response.json(); }) .then(data => { // Now you have your actual JSON data! const ORIGIN_DESTINATION_DATA = data; // Use the data in your app here }) .catch(err => console.error('Error loading large JSON:', err));
This way, your bundle stays small, and the JSON loads as a separate resource when needed.
Solution 2: Parse the JSON during build time (if you must)
If you absolutely need the JSON data embedded in your bundle (though I don't recommend it for 144MB—this will bloat your bundle drastically), you can use raw-loader to load the file as a string, then parse it manually:
- Install
raw-loaderfirst:
npm install raw-loader --save-dev
- Update your
webpack.config.jsto target this specific JSON file withraw-loader(instead offile-loader):
module.exports = { // ... other config module: { rules: [ // ... your other rules { test: /origin_destination\.json$/, // Target only this large JSON file use: 'raw-loader' } ] } };
- In your code, load and parse the string:
const jsonString = require('../../data/origin_destination.json'); const ORIGIN_DESTINATION_DATA = JSON.parse(jsonString);
Quick check for your Webpack config
Make sure your file-loader rule isn't matching all .json files accidentally. If you have a rule like:
{ test: /\.json$/, use: 'file-loader' }
This will turn every JSON file into a path string. Instead, narrow it down to only your large JSON file using a more specific test pattern (like the one in Solution 2) so smaller JSON files still get parsed normally by Webpack's built-in JSON loader.
内容的提问来源于stack exchange,提问作者John

