Profiles in React - reactjs

I'm trying to figure out how to run a react application (created through create-react-app) with different profiles.
That is, suppose I have several environments (local, dev, prod) and I have a fetch that refers to the backend (which is deployed on another server).
The backend has its own address for each environment. I need to somehow set global variables for different launches.
For example, in Springboot this can be done via application-"profile".properties.
I run the application through npm install -g serve & serve -s build. How to do it?

When working with create-react-app, you can configure your app using environment variables.
It is explained in detail in the documentation here: https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
All environment variables need to be prefixed with REACT_APP_.
You can define profiles with different environment variables using .env files.
For example, to set an API URL in production, create a file .env.production with the following contents:
REACT_APP_API_URL=https://my.beautiful.api/
…and as default (for local development), create a file .env:
REACT_APP_API_URL=http://localhost:3001/
The environment variables from the .env.production file will be used when you build your project with npm run build
The environment variables from the .env file will be used when you work on your project in local dev mode with npm start
Example for using the environment variable in your app's code:
fetch(process.env.REACT_APP_API_URL)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});

The way i handle this case is by using package react-native-config and i have create .env file (.env.dev, .env.staging, .env.prod) and i have define some scripts in the package.json. I am using react-native init project though.
as below
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest",
"postinstall": "sed -i '' 's/#import <RCTAnimation\\/RCTValueAnimatedNode.h>/#import \"RCTValueAnimatedNode.h\"/' ./node_modules/react-native/Libraries/NativeAnimation/RCTNativeAnimatedNodesManager.h",
"clean": "cd android && gradlew clean",
"feature": "node scripts/createfeature.js",
"component": "node scripts/createcomponent.js",
"android": "cd android && gradlew app:assembleDebug && gradlew installDebug",
"storybook": "storybook start -p 7007",
"prestorybook": "rnstl",
"android-dev": "SET ENVFILE=.env.dev && react-native run-android",
"android-staging": "SET ENVFILE=.env.staging && react-native run-android",
"android-prod": "SET ENVFILE=.env.prod && react-native run-android",
"ios-dev": "ENVFILE=.env.dev react-native run-ios",
"ios-staging": "ENVFILE=.env.staging react-native run-ios",
"ios-prod": "ENVFILE=.env.prod react-native run-ios",
"build-android-prod": "SET ENVFILE=.env.prod && cd android && gradlew assembleRelease"
},

Related

Best way to manage env variables for multiple environments

So, we have a React project. We have 3 branches: development, qa and staging. This is the code for the API URL in the 3 envs:
development:
const API_URL = process.env.NODE_ENV === 'development' ? 'https://our-website-development.com/api' : '/api';
qa:
const API_URL = process.env.NODE_ENV === 'development' ? 'https://our-website-qa.com/api' : '/api';
staging:
const API_URL = process.env.NODE_ENV === 'development' ? 'https://our-website-staging.com/api' : '/api';
Of course this has a problem: we have this conflict everytime we move things between environments.
So I want to move this to ENV variables.
But I have some doubts about how to implement it. I have some questions.
Option 1: have three .env files (.env.development, .env.qa, .env.staging) each one with the correct URL, push this file to the three branches, and then add scripts to start the project like npm start development or npm start qa.
Option 2. have only one .env file and don't push it to the project, make it static for every environment. This would mean having to manually change the endpoint url everytime I switch branches when developing.
Is there a better option?
Option 1 with some change will do the job. Keep 3 environment files and instead of using them in 3 branches, keep 3 npm tasks for start and build. While building ,keeping separate folders will be useful. Let me know if you need examples for this idea. I am using env-cmd to hook my .env files to my tasks.
Update:
Below is my scripts from Package.json, where I have 2 environments test and production,
"scripts": {
"start": "set PORT=41100 && env-cmd -f .env.test react-scripts start",
"build": "set \"GENERATE_SOURCEMAP=false\" && react-scripts build",
"build:test": "env-cmd -f .env.test npm run-script build && DEL /S /Q test && move build test",
"build:production": "env-cmd -f .env.production npm run-script build && DEL /S /Q production && move build production",
"test": "react-scripts test",
"format": "prettier --write src/**/*.ts{,x}",
"lint": "tsc --noEmit && eslint src/**/*.ts{,x}"
},
I am using Windows for development. If you are not this post may help to adjust your scripts,
Use custom build output folder when using create-react-app
Configurations flies are .env.test and .env.production and contents will look like,
REACT_APP_SOME_API = "https://myurl/api/resource"

define .env file except default env file in react app

I need to load for each development/production server a different .env file.
localhost | .env.localhost
development | .env.development
production | .env.production
base on react documentation, by default we can use .env.development and .env.production
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
but i want to use new environment variable as localhost. how can i do that? i want to run one of my script by .env.localhost variable's file.
you can modify script part of package.json from:
"start": "react-scripts start"
for Linux and MacOS to:
"start": "PORT=3006 react-scripts start"
Windows to:
"start": "set PORT=3006 && react-scripts start"
And if you want to set new variables in environment. Then add then in .env files of shell, but start name with REACT_APP for ex
REACT_APP_MY_VAR

Create multiple react builds, based on different configuration files

I have a web app created with create-react-app. Instead of having just one build folder generated via "yarn build" I need to have multiple build folders each using a different configuration file (for database connection etc).
How can I do that?
Yes, it is possible. Just define another build script.
Find script in package.json something like this:
"scripts": {
"start": "node scripts/start.js",
"build": "npm run git-info && node scripts/build.js",
"test": "git-info && node scripts/test.js --env=jsdom",
"git-info": "git log -1 --pretty=format:\"%h%x09%x09%ad%x09%s\" > src/static/gitInfo.txt"
},
You can define something like this:
"scripts": {
"build": "npm run git-info && node scripts/build.js && node scripts/build2.js && node scripts/build3.js",
},
When you call yarn build , its called all commends in build section (npm run git-info && node scripts/build.js && node scripts/build2.js && node scripts/build3.js)
(yarn or npm...)
In your build script scripts/build.js, scripts/build1.js, ... you can define what you want (output folders, etc...)
Assuming you have one configuration file per environment, you could have a build script that takes the config as an argument or that reads from process.env and then you load the right .env file for each build.
"scripts": {
"build": "dotenv-cli -e .env.production node build.js",
"build:staging": "dotenv-cli -e .env.staging node build.js",
"build:dev": "dotenv-cli -e .env.dev node build.js",
}
Here, build.js would be a custom JS file that you wrote and it would build your app.
Keep in mind that you'd need to output the built files in a way that they don't overwrite each other as you build for different environments.

create react app not picking up .env files?

I am using create react app to bootstrap my app.
I have added two .env files .env.development and .env.production in the root.
My .env.development includes:
API_URL=http://localhost:3000/api
CALLBACK_URL=http://localhost:3005/callback
When I run my app using react-scripts start and console out process.env it spits out
{ NODE_ENV: "development", PUBLIC_URL: "" }
I've tried different things, but its just not picking up the veriables in my development file, what am I doing wrong?!
Directry structure is:
/.env.development
/src/index.js
Package.json script is:
"start": "export PORT=3005; npm-run-all --parallel server:start client:start",
"client:start": "export PORT=3005; react-scripts start",
"server:start": "node server.js",
"build": "react-scripts build",
Edit:
#jamcreencia correctly pointed out my variables should be prefixed with REACT_APP.
Edit 2
It works okay if I name the file .env but not if I use .env.development or .end.production
With create react app, you need to prefix REACT_APP_ to the variable name. ex:
REACT_APP_API_URL=http://localhost:3000/api
REACT_APP_CALLBACK_URL=http://localhost:3005/callback
** Make sure your .env file is in the root directory, not inside src folder.
CRA Docs on Adding Custom Environment Variables:
Note: You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name
Make sure your .env file is in the root directory, not inside src folder.
Had this same problem! The solution was to close the connection to my node server (you can do this with CTRL + C). Then re-start your server with 'npm run start' and .env should work properly.
Source: Github
If you want to use multiple environment like .env.development .env.production
use dotenv-cli package
add .env.development and .env.production in project root folder
and your package.json
"scripts": {
"start": "react-app-rewired start",
"build-dev": "dotenv -e .env.development react-app-rewired build",
"build-prod": "dotenv -e .env.production react-app-rewired build",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom",
"eject": "react-scripts eject"
},
then build according to environment like
npm run-script build-dev
I was having the same problem, but it was because I had my .env file in YAML format instead of JS.
It was
REACT_APP_API_PATH: 'https://my.api.path'
but it needed to be
REACT_APP_API_PATH = 'https://my.api.path'
For people who apply all those answers above and didn't work just restart the terminal of npm start, stop the live server and run it again and it will work because it works for me
Regarding env-cmd. As per VMois's kind post on gitHub, env-cmd has been updated ( version 9.0.1 as of writing ), environment variables will work as follows on your React project:
"scripts": {
"build:local": "env-cmd -f ./.env.production.local npm run build",
"build:production": "env-cmd -f ./.env.production npm run build"
}
In your package.json file.
1- Make sure .env file is based your react app root directory
2- for react app you need to prefix REACT_APP_ to the variable name. ex: REACT_APP_API_URL
3- kill server and npm start again after .env file modify
For this purpose there is env-cmd module. Install via npm npm i env-cmd then in your package.json file in scripts section:
"scripts": {
"start": "env-cmd .env.development react-scripts start",
"build": "GENERATE_SOURCEMAP=false env-cmd .env.production react-scripts build",
}
In your project root you have to create two files with the same env variables but with different values:
.env.development
.env.production
Then exclude them from public. For this in your .gitignore file add two lines:
.env.development
.env.production
So this is a proper way to use different env variables for dev and prod.
While working with .env file, be it frontend or backend.
Whenever you modify the .env file, you must restart the respective server for the changes to take effect in the application.
Hot reloading doesn't read changes from .env file.
If the .env file works but .env.development or .env.production don't, then create an empty .env file alongside those two. I don't know why but this works for me.
Your project can consume variables declared in your environment as if they were declared locally in your JS files. By default you will have NODE_ENV defined for you, and any other environment variables starting with REACT_APP_.
Reference: https://create-react-app.dev/docs/adding-custom-environment-variables
that doc creates confusion.
So you actually need to put prefix REACT_APP_ within the .env to make it work.
And make sure that you restart the test/dev/prod server because the .env content change was loaded on the build stage.
And remember not to have semi-colon after the API key in the env-file.
REACT_APP_API_KEY = 'ae87cec695cc4heheh639d06c9274a';
should be
REACT_APP_API_KEY = 'ae87cec695cc44heheh1639d06c9274a'
that was my error
when you get undefined from the environment file then just stop the terminal and restarts with npm start command.
For any VS Code users, be aware that the .env.local env file is auto-sourced, but also auto-ignored from search results when you do a project wide search for MY_ENV_VAR(probably due to it being git ignored by default). This means that if you have MY_ENV_VAR= in your .env.local like me and forgot about it, it'll break things and you'll spend 15 mins being very confused.
Was struggling for a good hour before I noticed my kind IDE added an import:
import * as process from "process";
just remove it and you're fine, if that's your case as well.
After you add .env file, you need to
restart your application
kill the server
run npm start again
And it should work
I had same issue that I wasn't able to access .env variable in App.js.
and I had solved the problem use create correct .env file.
in my case I was copy file from different OS and use in ubuntu system
so just I did "sudo touch .env" and added my variables and restart app again then it's working for me.
I forget to add process.env.
It looks like this
const domain = process.env.REACT_APP_AUTH0_DOMAIN;
first step:
in your .env.local file add REACT_APP_your_API_key in this way
second step:
Add your config file ${process.env.REACT_APP_Your_API_key}
the third step:
must restart your React App and then Test whether it works.
mainly, I forget the last step
If none of the solutions above worked for you, give these potential solutions a shot:
Make sure all the import statements within the file that is requiring defined environmental variables are being imported from the local project and not some other project(VSCode wrongly autocompleted some of my import statements in this manner)
Try exiting your current Terminal instance and running the app in a new instance
I made the silly mistake of naming my file secret.env because that's how I always did it in Node.js.
After changing the name to .env, restarting the terminal, and running npm start again, everything worked like a charm
I didn't get any value back as well. For some reason, I thought the environment file should be dev.env, qa.env etc. Actually, it's just ".env". That's that. In case some else makes this mistake.
create-react does not supports hot reload feature .env files since they are not Javascript. So, when you change the env files make sure to manually start your server to see the effect of new changes.
In my case, a manual restart of the server worked fine :)
What worked for me was to install env-cmd and after that in my package.JSON add the following line of code
"scripts": {
"start": "env-cmd -f .env.development react-scripts start ",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
As of latest react-scripts (3.2.0) it's a simple as putting say
PORT=4000
BROWSER=none
in your .env or .env.development file (..etc) which is supposed to be in the root folder.
It will NOT work with then REACT_APP prefix (the docs are outdated I guess) and it does NOT require any extra npm packages (react-scripts already includes dotenv 6.2.0)

What are these targets in node for?

I have the following in my package json that is responsible for building and running the Angular 2 application. May I know the meaning of each of the flags in the targets ? This for deploying an Angular 2 application in IBM Bluemix
"build": "rimraf dist && webpack --progress --profile --bail",
"start": "tsc && concurrently \"tsc -w\" \"lite-server\" "
The answer to your questions are located in the documentation for each of the node js libraries:
https://www.npmjs.com/package/rimraf
https://www.npmjs.com/package/concurrently
https://www.npmjs.com/package/tsc
https://www.npmjs.com/package/webpack
https://www.npmjs.com/package/lite-server
The build script is deleting the dist folder, then building your app with webpack.
The start script is compiling your typescript and then running the typescript compiler in watch mode and then starting lite-server concurrently.

Resources