You can consider dynamic import instead to solve your case, an example of using it would be as follow:
function Component() {
const [json, setJson] = useState(null);
useEffect(() => {
import('./some.json').then((res) => setJson(res));
}, []);
return <pre>{JSON.stringify(json)}</pre>;
}
In most build tools, dynamic import will cause it to split into an additional chunk / file, which is not bundled in the initial bundle / entry file and should make the initial loading fast even if it the content in the JSON file is large.
An alternative "hack" would be change your .json
extension to match with those images. Based on the documentation of create-react-app
. The extension that ends with bmp
, gif
, jpg
, jpeg
and png
, will automatically be loaded with file-loader
.
Assuming your CDN / file servers doesn't have CORS restriction, you can then rename your .json
file to .jpg
and obtain the URL generated from there, usage sample below:
import theJsonFile from './some.json.jpg';
const [json, setJson] = useState(null);
useEffect(() => {
fetch(theJsonFile)
.then((res) => res.json())
.then((json) => setJson(json));
}, []);
return <pre>{JSON.stringify(json)}</pre>;
(It is not the best idea, as Content-Type
/ CORS and other stuff can mess with it, but it is worth a try for small project)