React中使用JSON文件时如何修复‘Module build failed: SyntaxError: Unexpected token’错误?
Hey there! Let's work through this JSON import issue you're facing while following Brian Holt's React tutorial. The error ERROR in ./data.json Module build failed: SyntaxError: Unexpected token, expected [ usually points to a couple of common issues with Webpack 2 setup or JSON formatting—let's break down the fixes step by step:
1. Remove the redundant json-loader (Webpack 2 has built-in JSON support!)
Webpack 2 and above natively handles JSON files without needing the json-loader package. Adding it manually can actually cause conflicts. Here's what to do:
- Open your
webpack.config.jsfile - Look for any rule like this and delete it:
{ test: /\.json$/, loader: 'json-loader' } - Save the config and try rebuilding your project.
2. Validate your JSON file syntax
The "Unexpected token" error almost always means your data.json has invalid syntax. JSON has strict rules:
- All keys and string values must use double quotes (no single quotes allowed)
- No trailing commas at the end of arrays or object properties
- Make sure brackets/ braces are properly closed
Example of valid JSON:
{ "products": [ { "id": 1, "name": "Sample Product", "price": 19.99 } ] }
Quick way to test: Copy your JSON content into your browser's console and run JSON.parse(yourJsonString)—it'll throw an error pointing to the exact problematic line if there's an issue.
3. Double-check your import syntax
Make sure you're importing the JSON correctly in your React component:
// ES6 import (preferred for React) import data from './data.json'; // OR CommonJS require (also works) const data = require('./data.json');
Ensure the file path is correct relative to your component file—typos here can sometimes trigger unexpected errors too.
4. Ensure Babel isn't trying to process JSON files
Check your Webpack rules to make sure Babel only targets JavaScript/JSX files, not JSON. Your Babel rule should look like this:
module: { rules: [ { test: /\.jsx?$/, // Only matches .js and .jsx files exclude: /node_modules/, loader: 'babel-loader' } // No rules targeting .json files here! ] }
If Babel is accidentally trying to transpile your JSON, it'll throw syntax errors since JSON isn't JavaScript.
5. Clear Webpack cache and rebuild
Sometimes cached build files can cause weird, persistent issues. Try:
- Deleting the
node_modules/.cachefolder (if it exists) - Running your build command with the
--no-cacheflag, e.g.:npm run build -- --no-cache
Give these steps a try—most likely either the redundant json-loader or invalid JSON syntax is the culprit.
内容的提问来源于stack exchange,提问作者Ma'mun

