How to use global configuraion in react - javascript

Recently I am studying ReactJS.
I want to set a global configuration variable such as SERVER_IP_ADDR.
So, when I ask the server for an API (get / post) as Ajax,
I would like to use this global configuration variable in ReactJS.
I usually create a global variable in JavaScript,
Just import it and use it anywhere.
/js/config.js
var SERVER_IP_ADDR
/js/main.js
<script src="/js.config.js"></script>
and like this
<script>
function request() {
url = SERVER_IP_ADDR;
}
</script>
Can not I set up this structure in ReactJS?

You could export a configuration object and import it wherever you need it.
js.config.js
const config = {
SERVER_IP_ADDR: '...',
OTHER_CONFIG_KEY: '...'
}
export default config;
and in the file you need it
import configuration from "./js.config"
function request(){
fetch( configuration.SERVER_IP_ADDR );
}

If you use create-react-app, You should use .env variables for such thing.
Add .env file in your root path, file content would be like this:
REACT_APP_SERVER_IP_ADDR=http://myapi.com
REACT_APP_CUSTOM_VARIABLE=foobar
then in your source code, you can use it like this:
${process.env.REACT_APP_SERVER_IP_ADDR}/v1/user
More info regarding .env: .env

yes you can , you can use the config.js file and use it multiple places.
your config.js file looks like
module.exports={
url : 'api.xxx.com'
}
and you can import it like
import config from './config';
config.url

Related

Referencing vanilla js file in TypeScript getting file is not a module

I'm trying to import a file into TypeScript that's basically just a js file that you'd put into a tag. I've tried a few different things.
// global.d.ts
declare module 'myfile.js'
Inside of the react file:
// component.tsx
import { foo } from '../lib/myFile.js' // This is saying it is not a module
Inside of the js file, it looks like this a few times so not sure how I need to reference the file:
(function( something ) {
something.Foo = function (){}
}(window.something = window.something || {}));
Any thoughts on how I could use this file? Do I need to go through and declare typings for everything in it?
EDIT: I've added allowJS to my tsconfig but it still doesn't work.
You can only import what is exported from the file.
If your file contains only immediately invoked functions, or top level code, you only need to import the file itself like this:
import '../lib/myFile.js'
This is a little weird, however. I would suggest wrapping everything with a function and exporting then importing that function instead.

Use env variable in helper file (Gatsby)

I have a Gatsby project that looks a bit like this:
File structure
- src
- pages
- Homepage.js
- helpers
- customFetch.js
Homepage.js
import React, { useEffect } from 'react'
import customFetch from '../helpers/customFetch'
export default function Homepage() {
useEffect(()=>{
setInterval(() => {
customFetch('/my-endpoint').then((result)=> {
// Do something...
})
}, 5000);
}, [])
return (
<div>
Homepage content here
</div>
)
}
customFetch.js
export default function customFetch(path) {
const apiURL = 'https://api.mysite.com'
// Do something fancy here...
return fetch(`${apiURL}${path}`)
}
What I want to do is to bring apiURL from a .env.* file instead of hard coding it. How could I do it the Gatsby way? Thanks!
PS.: I know that doing this inside a page is trivial (https://www.gatsbyjs.org/docs/environment-variables/) but that's a bit different than what I want to do.
First of all, you need to set up your environment in your build and develop command like this (in your package.json):
"build": "GATSBY_ACTIVE_ENV=yourEnvironment gatsby build",
"develop": "GATSBY_ACTIVE_ENV=yourEnvironment gatsby develop",
The snippet above will get the configuration from .env.yourEnvironment file. Then, you need to create your environment file and define your desired variables, such as (.env.yourEnvironment):
API_URL=https://api.mysite.com
Then, in your gatsby-config.js (outside module.exports) you need to require that environment file:
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})
According to Gatsby documentation, this is because:
Project environment variables that you defined in the .env.* files
will NOT be immediately available in your Node.js scripts. To use
those variables, use NPM package dotenv to examine the active .env.*
file and attach those values. dotenv is already a dependency of
Gatsby, so you can require it in your gatsby-config.js or
gatsby-node.js like this:
The last step is to get your variable in your component using:
const apiURL = process.env.API_URL
In your case:
export default function customFetch(path) {
const apiURL = process.env.API_URL
// Do something fancy here...
return fetch(`${apiURL}${path}`)
}
That allows you to separate the logic and token and environment variables to implement a multisite (multidomain) project for example.

Cordova plugin overrides a default TypeScript namespace

I have installed cordova-plugin-file. This is implemented like so:
import { File } from 'cordova-plugin-file';
constructor(file: File) { ... }
....
But now I'm trying to access the Javascript File.
Although when I'm trying to create a normal File like so:
let myFile = new File(blob, name, mimeType);
The plugin name overrides the default File name which makes this option illegal.
Is there a way I can still use the javascript File and using the plugin in the same class?
Use an alias for your import:
import { File as FileCordova } from 'cordova-plugin-file';

Import external js File in Angular 4 and access functions and variables

Maybe my title is a bit unclear, so I will try to explain my problem with a simple task.
Lets say I have a the following Javascript File "file.js":
var number = 4;
function encode(){
console.log("encode in "file.js" has been called...");
}
I place this script in my angular4 project in "src/assets/js/file.js".
In ".angular-cli.json" I add the path of the script
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"./assets/js/modernizr.js",
"./assets/js/webflow.js",
"./assets/js/file.js"
Now my question is how can import or use this script file in my app.module.ts or any other component, without adding it to index.html
I tried several ways:
import * as test from 'assets/js/file.js';
import {test} from 'assets/js/file.js';
declare var file: any;
Unfortunately, none worked...
I would really appreciated it, if you guys could help me out.
You can use system.js to import file at runtime as below, you have to add systemjs in node_modules.
System.import("src/assets/js/file.js").then(fileInstance => {
console.log(fileInstance);
});
In component.ts you should declare the name of the function you want to use.
declare let encode:any
ngOnInit(){
encode()
}
You can Import js locally to ts file like this : import '../../../scripts/custom.js';
then declare method name in custom.js that you want to use like this 👍
declare var fAlert;
then in a place like ngOnInit directly use this method
fAlert();

Import JSON file in React

I'm new to React and I'm trying to import a JSON DATA variable from an external file. I'm getting the following error:
Cannot find module "./customData.json"
Could some one help me? It works if I have my DATA variable in index.js but not when it's in an external JSON file.
index.js
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import customData from './customData.json';
import Profile from './components/profile';
import Hobbies from './components/hobbies';
class App extends Component {
render() {
return (
<div>
<Profile name={this.props.profileData.name}imgUrl={this.props.profileData.imgURL} />
<Hobbies hobbyList={this.props.profileData.hobbyList}/>
</div>
);
}
}
ReactDOM.render(<App profileData={DATA}/>, document.querySelector('.container'));
hobbies.js
import React, {Component} from 'react';
var Hobbies = React.createClass({
render: function(){
var hobbies = this.props.hobbyList.map(function(hobby, index){
return (<li key={index}>{hobby}</li>);
});
return (
<div>
<h5>My hobbies:</h5>
<ul>
{hobbies}
</ul>
</div>
);
}
});
export default Hobbies;
profile.js
import React from 'react';
var Profile = React.createClass({
render: function(){
return (
<div>
<h3>{this.props.name}</h3>
<img src={this.props.imgUrl} />
</div>
)
}
});
export default Profile
customData.json
var DATA = {
name: 'John Smith',
imgURL: 'http://lorempixel.com/100/100/',
hobbyList: ['coding', 'writing', 'skiing']
}
export default DATA
One nice way (without adding a fake .js extension which is for code not for data and configs) is to use json-loader module. If you have used create-react-app to scaffold your project, the module is already included, you just need to import your json:
import Profile from './components/profile';
This answer explains more.
This old chestnut...
In short, you should be using require and letting node handle the parsing as part of the require call, not outsourcing it to a 3rd party module. You should also be taking care that your configs are bulletproof, which means you should check the returned data carefully.
But for brevity's sake, consider the following example:
For Example, let's say I have a config file 'admins.json' in the root of my app containing the following:
admins.json
[{
"userName": "tech1337",
"passSalted": "xxxxxxxxxxxx"
}]
Note the quoted keys, "userName", "passSalted"!
I can do the following and get the data out of the file with ease.
let admins = require('~/app/admins.json');
console.log(admins[0].userName);
Now the data is in and can be used as a regular (or array of) object.
With json-loader installed, you can use
import customData from '../customData.json';
or also, even more simply
import customData from '../customData';
To install json-loader
npm install --save-dev json-loader
Simplest approach is following
// Save this as someJson.js
const someJson = {
name: 'Name',
age: 20
}
export default someJson
then
import someJson from './someJson'
React 17 created from create-react-app, importing json just work by default.
import config from './config.json'
The solution that worked for me is that:-
I moved my data.json file from src to public directory.
Then used fetch API to fetch the file
fetch('./data.json').then(response => {
console.log(response);
return response.json();
}).then(data => {
// Work with JSON data here
console.log(data);
}).catch(err => {
// Do something for an error here
console.log("Error Reading data " + err);
});
The problem was that after compiling react app the fetch request looks for the file at URL "http://localhost:3000/data.json" which is actually the public directory of my react app. But unfortunately while compiling react app data.json file is not moved from src to public directory. So we have to explicitly move data.json file from src to public directory.
Please store your JSON file with the .js extension and make sure that your JSON should be in same directory.
// rename the .json file to .js and keep in src folder
Declare the json object as a variable
var customData = {
"key":"value"
};
Export it using module.exports
module.exports = customData;
From the component that needs it, make sure to back out two folders deep
import customData from '../customData';
In current react build you simply import and use:
import jsonData from 'path/to/myJson.json'
try with export default DATA or module.exports = DATA
there are multiple ways to do this without using any third-party code or libraries (the recommended way).
1st STATIC WAY: create a .json file then import it in your react component example
my file name is "example.json"
{"example" : "my text"}
the example key inside the example.json can be anything just keep in mind to use double quotes to prevent future issues.
How to import in react component
import myJson from "jsonlocation";
and you can use it anywhere like this
myJson.example
now there are a few things to consider. With this method, you are forced to declare your import at the top of the page and cannot dynamically import anything.
Now, what about if we want to dynamically import the JSON data? example a multi-language support website?
2 DYNAMIC WAY
1st declare your JSON file exactly like my example above
but this time we are importing the data differently.
let language = require('./en.json');
this can access the same way.
but wait where is the dynamic load?
here is how to load the JSON dynamically
let language = require(`./${variable}.json`);
now make sure all your JSON files are within the same directory
here you can use the JSON the same way as the first example
myJson.example
what changed? the way we import because it is the only thing we really need.
I hope this helps.
var langs={
ar_AR:require('./locale/ar_AR.json'),
cs_CZ:require('./locale/cs_CZ.json'),
de_DE:require('./locale/de_DE.json'),
el_GR:require('./locale/el_GR.json'),
en_GB:require('./locale/en_GB.json'),
es_ES:require('./locale/es_ES.json'),
fr_FR:require('./locale/fr_FR.json'),
hu_HU:require('./locale/hu_HU.json')
}
module.exports=langs;
Require it in your module:
let langs=require('./languages');
regards
This worked well in React 16.11.0
// in customData.js
export const customData = {
//json data here
name: 'John Smith',
imgURL: 'http://lorempixel.com/100/100/',
hobbyList: ['coding', 'writing', 'skiing']
}
// in index.js
import { customData } from './customData';
// example usage later in index.js
<p>{customData.name}</p>
My friends, if you are using React and TypeScript, just do these steps and DONE!
In the tsconfig.json add these 2 new lines:
// tsconfig.json
{
"compilerOptions": {
// ... other options
"esModuleInterop": true,
"resolveJsonModule": true
}
}
Import your json:
import yourJSON from "./data/yourJSON.json"
Something that worked for me was to simply place the JSON file in the public folder. You can simply import in any js using
brain.loadData("exampleFile.json");
It is as simple as that I guess. Definitely worth a try :D

Categories