Reputation: 4374
My React code builds a UI reading a JSON file. However, this file becomes a part of the react build
. How can I keep this from minifying, and keep it as a separate file in a folder 'data/data.json'
. Right now I have a data folder inside src
.
I want to be able to change the JSON file which will, in turn, change the UI.
Upvotes: 6
Views: 2536
Reputation: 46
You need to use Webpack to configure build settings if you haven't yet. You can use this tutorial on how to install it.
Install Copy Webpack Plugin: npm i --save copy-webpack-plugin
Go to the project's webpack.config.prod.js
and webpack.config.dev.js
(If you run build in development mode), use this configuration for an example of src/assets/example.json
import CopyWebpackPlugin from 'copy-webpack-plugin';
export default {
plugins: [
new CopyWebpackPlugin([
{ from: 'src/assets/example.json', to: 'assets/example.json' }]
)
]
}
This configuration extracts the JSON file from the src
folder and prevents it from being minimized.
Upvotes: 1
Reputation: 546
Fetch a request to get the file data instead of importing or requiring it. example:
fetch(URL, {method:'GET'})
.then(response => response.json())
.then(json=>{
//use the json data
})
If you are using redux, I suggest you to use the fetch request in your action and store data. If not, run the fetch request inside the componentDidMount and store data in your component state, which lets you pass data to children components.
Upvotes: 2