How to read window variables as .json or value key pais outside of /SRC folder on ReactJS during development and production mode
When our application is getting bigger and its settings were hardcoded like the endpoints for instance among other settings, and after making an npm run build you must make an update to any endpoint then you've got not any other choice but to recompile everything again with npm run build and take it to production again, so for this special scenario it is easier to have an external config.js file with all the endpoints inside of it or extra settings your app needs which can be changed through time.
to be able to see this working let's create a project running on your terminal npx create-react-app "give a name to your app, in my case this one was called withproperties"
open your application with your favorite code editor and go to the public folder and let's create over there a file called config.js or any other name you wish to give it, and inside of it paste this:
window.endpointone = {
"enpointOne": "service.com/api/one", "endpoinTwo": "service.com/api/two" }; window.othersettings = { "exampleSettingOne": "settingsOne", "exampleSettingTwo": "settingsTwo", }; |
we are just going to be taking advantage of the variable window all over the application as global variables
now let's open inside the public folder the index.html file and under root tag let's do this
<div id="root"></div>
<script type="text/javascript" src="config.js"></script>
|
now you can use those variables all over the application just by using the window variable like this
window.endpointone.enpointOne or window.endpointone.endpoinTwo
or window.othersettings.exampleSettingOne
if you want to see it in action just replace you App.js by this code
import React from 'react';
import logo from './logo.svg'; import './App.css'; class App extends React.Component { constructor() { super(); this.state={ endpointOne:'', endpointTwo:'', endpointThree:'', } } componentDidMount() { this.setState({ endpointOne:window.endpointone.enpointOne, endpointTwo:window.endpointone.endpoinTwo, }) console.log('data '+window.endpointone.endpoinTwo); } render() { return( <div> <h1>Data loaded from file called config.js</h1> <hr/> <p>Endpoint 1 : <strong>{this.state.endpointOne}</strong></p> <p>Endpoint 2 : <strong>{this.state.endpointTwo}</strong></p> <p>//***********************************//</p> <p>Other Settings 1 : <strong>{window.othersettings.exampleSettingOne}</strong></p> <p>Other Settings 2 : <strong>{window.othersettings.exampleSettingTwo}</strong></p> </div> ); } } export default App; |
run the application and test it, so now let's make an npm run build and after it has been build there is a file outside called config.js which we can edit at any time
Comments
Post a Comment