Importing JSON in TypeScript does not import the contents but a URL
As @T.J. Crowder
rightfully suggested the problem comes from my misunderstanding of the asset/resource
loader in Webpack 5
. According to the documentation:
asset/resource emits a separate file and exports the URL. Previously achievable by using file-loader.
My goal here is to copy videos-info.json
from /src/
into the /dist
folder when I do npm run build
, so that I can host it statically somewhere and set up an AWS Lambda to overwrite it on regular intervals. Therefore, I cannot load the JSON inside the client.bundle.js
through Webpack because the data will be hardcoded in the bundle. This note about how Webpack builds resources statically helped me understand it better: https://stackoverflow.com/a/44424933/9698467
Therefore I must use asset/resource
loader in Webpack 5 to produce a URL, which I can later load into the webpage via a React hook
for example:
const videosFile = require('./videos-info.json');
// videosFile is a URL
React.useEffect(() => {
const resp = await fetch(videosFile);
const data = await resp.json() as VideoResult;
const videos: VideoResultItem[] = data.items;
}, []);