Read in JSON at runtime in React Webpack app - javascript

I have a small React/Webpack app where I import a JSON file at the top of the file. At buildtime, the contents of the JSON are read into the resulting bundle.js. If I then make changes the the JSON file I need to re-build the app for the React app to change.
Is there a way to get it so the React app will read in the JSON file at runtime?
One idea I had was to manually edit the output HTML to read mydata.js (in addition to bundle.js) and then mydata.js would just assign window.mydata to the data. Then the React app would read in from the window global object. But I think that's a hacky solution curious to see if there are better paths. Thanks!

You can move the json file in the public folder of your react app (so it's served as a static asset) and then use a fetch call to access it. Attention: this will be much slower at execution time (as the browser needs to execute an additional HTTP request).

Related

How to pass/import server-side JSON to a vue app?

I'm building a webapp that requires a JSON file as data. The person using my app in their website should be able to pass in a JSON file hosted on their server so that my app can read it.
In development, I just used import mydata from "./mydata.json", but this won't work in production. I tried to have a computed property that returns require (this.publicPath + this.datapath) (where this.publicPath is process.env.BASE_URL, but it's not able to find the file (if it's relevant, I'm using vue-cli to build).
The structure of my app is that I have a wrapper App.vue and then the main component, main-component.vue (so that I can pass a prop containing data to the main component).
What's the best way to do this? I've tried using a <script> tag in index.html, but apparently that's not supported with JSON. I don't want to use other libraries like jQuery.
(I'm thinking that I could have the user just import their file with the ES6 syntax by creating a new Vue component/app, but I'm not sure how to do that in pure HTML).
As an extension of my comment: what you're looking for is to actually fetch the JSON from your server using an XMLHttpRequest. You can do this in a modern, ES6-manner using the Fetch API:
fetch('/path/to/your/json')
.then(resp => resp.json())
.then(data => {
// Access the parsed JSON as `data`
console.log(data);
});
If you can try using a .js file that migh work and you can structure the data the same way as in a .json file, afterall a json is just a js object, also i had this problem while doing the same thing.
DISCLAIMER: you might have to restructure your data to be in an exported variable if that is possible, like so:
export const myObj = {your json}

React JS - Reading environment configurations from external property file

Problem :
I am new to React JS, and looking for an option to read environment configs from an external property file. This problem is more specific for one of my clients, who is looking to have an option to change the environment files dynamically. E.g. change the hostname/port dynamically whenever there is a change. The build process is not owned by my client. I create a minified final package, which my client deploys it on tomcat/web server.
Tried Solution :
With some read-outs, I have configured .env files for different environments and able to successfully read configs from these files. However, these are more of a build process environment files. And, I am trying to find a way to read the configs from an external source after my package is created.
Possible solutions : Here is one possible approach I can think of -
Read external property file using libraries like "properties-reader". I will provide the property file as part of my release bundle (i.e. build folder). My client can change this property file whenever required.
Please suggest if this is the correct approach or is there a better solution to this problem?
A Solution which worked for me !!
1) Create a "config.js" file inside public folder of react project. Sample Content of the
"config.js" file -
window.env = {
API_DOMAIN_ADDR: "http://localhost:8080"
};
2) Refer "config.js" file inside index.html. Code for index.html will be -
<body>
<div id="root"></div>
<script src="%PUBLIC_URL%/config.js"></script>
</body>
3) Now, content of the config.js file will be accessible to react code. Sample code to retrieve the value of config.js variables -
window.env.API_DOMAIN_ADDR
Add this code wherever variable value needs to be accessed. I added this in my service class which is making ajax call.
I would suggest using something like Firebase Realtime DB. I had a similar requirement for pointing the App builds to production or development server APIs for my company. For this, we use to load a Firebase Config and from there the UI used to pick up the host server endpoint.
Advantages:
This saves you from deploying your build folder every time.
This is realtime and less prone to errors.
FirebaseDB is free for small stuff like this.
The second option is to create two environment files which I see you have already done.

How can I serve remote React app with a script tag?

We have at our company a react app (built with create-react-app) which is served today via an iframe, which works well.
A need has risen to serve the app (which is always embedded within other pages), with a script tag alone (no iframe tag).
I thought of something like:
<div id="app-placeholder"></div>
<script src="https://our-app.com/init.js"></script> // this will create a function called window.InitMyApp
<script>
InitMyApp('#app-placeholder', 'token', otherOptions)
</script>
I've tried to create init.js file in the react app's public folder. I can access the file.
From that file, how can I render the react app itself to the given selector (#app-placeholder)?
Because this file is served as-is, and doesn't get transpiled by webpack/babel, I cannot use import/jsx/require() and other stuff.
Am i on the right track?
Should I manually transpile this file?
Are there any other solutions to this rendering method?
You should try configuring the compiler with { output.library }. This should produce a compilation output that's ready for distribution, which means you can easily reference it in another document (and not need to worry about, say, transpiling/optimizing sources, because this was already performed by webpack).
Here's an example of a multi-part library produced by webpack. As you can see, the entrypoint exports are being assigned to window.

How to read a value from properties file in a javascript file

I have a spring-boot project which serves angularjs. Both the front-end and back-end code are in the same project.
In my angularjs service.js files I am calling the back-end service.
I have different urls in the different properties file. I want to read them as per profile selection. I know how to read properties file in a Java class but I am not sure how to read values from properties file in a javascript file.
As shown below:
Some options:
create a separate config.json for your angular APP (manage it manually).
use maven resource plugin to filter placeholders for your config.json file (automated). E.g. read in one place and substitute in another (but I don't like this way).
Or create an API to return data from from your properties file as JSON.
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

How to load large list of JSON files from local directory into react app

I have been given 100+ JSON files which I need to display locally in a react app. I'm able to load one file at a time using the fetch() function, but I'm not sure how to load all of the files.
I've considered getting a list of all of the files and then doing a fetch() on the list, but the issue is that I cannot access the list of files in the directory.
I read that I could use fs but it seems like that won't work in the browser. ex: I've tried:
var fs = require('fs');
var files = fs.readdirSync('../app/components/data/');
but this throws the error: fs.readdirSync is not a function. I'm open to different approaches.
If the files are small, one option would be to merge them all into one large JSON array in one file and fetch() that. If you don't mind load times taking a bit of a hit, you could even import or require() the JSON file from your application code, including its contents in your JS bundle.
However, if the files are big, you're probably better off creating a 'manifest' file which describes the contents and locations of the other files. It wouldn't be too hard to write a script to store all the files in that directory in an array in an index.json. From there, you could fetch() the index from the browser, and then fetch() each file individually.

Categories

Resources