After creating a new web app with create-react-app (CRA), I need to include some environment files for configuring various endpoints. Noticed that CRA comes with the cool dotenv package all ready to go. There's only one problem with that - I would like to have dotenv read these files from within my ./environments directory and not the root directory. Is there any way to load the .env, .env.local, .env.test, etc... files in a directory separate from the root directory?
Noticing I can achieve this in my express backend server.js by simply importing like so:
require('dotenv').config({ path: `./environments/` })
Can I do the same with my client-side code in React? If so, where should I put this import? Doesn't seem to work for me.
If you created your project using CRA and want to configure dotenv to change the path from where it loads the env files, you will have to do npm eject.
Alternatively, you can use env-cmd to achieve the same:
Installation:
npm i env-cmd
Add scripts in package.json, for example:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"dev": "env-cmd -f envs/.env.dev react-scripts build",
"qa": "env-cmd -f envs/.env.qa react-scripts build",
"demo": "env-cmd -f envs/.env.demo react-scripts build"
},
After creating .env.dev, .env.qa, .env.demo in envs/ directory.
Now, you can run:
$ npm run dev // it will use envs/.env.dev file
$ npm run qa // it will use envs/.env.qa file
$ npm run demo // it will use envs/.env.demo file
Related
when I issue below command to start react app facing this error, can anyone help.
npm start
react_template#0.1.0 start
env-cmd -f .env.dev craco start
'env-cmd' is not recognized as an internal or external command,
operable program or batch file.
Did you install cross-env with npm? Try running
npm install
This should work.
its really hard to tell without taking a look at your package.json file. but i see that you're using env-cmd package which provides custom run and build commands and lets you have multiple environment declarations.
here is an example of what you can do with it in your package.json (this example is a nextjs example)
"scripts": {
"dev": "env-cmd -f env/.env.local next dev",
"build:pre": "env-cmd -f env/.env.pre next build",
"start:pre": "env-cmd -f env/.env.pre next start",
"build:stg": "env-cmd -f env/.env.stg next build",
"start:stg": "env-cmd -f env/.env.stg next start",
"build:rc": "env-cmd -f env/.env.rc next build",
"start:rc": "env-cmd -f env/.env.rc next start",
"build:prod": "env-cmd -f env/.env.prod next build",
"start:prod": "env-cmd -f env/.env.prod next start"
},
as you can see i created a build and run command for each environment and i also provided a .env.ENVNAME file for my config. the env/,env.ENVNAME is the path of my .env files. the env folder is in the root of the project.
here is how to run and build the app with env-cmd for above scripts:
npm run build:Env_name
for example for building my stg env:
npm run build:stg
or for starting the app
npm run start:Env_name
for example:
npm run start:stg
in your local you can use npm run dev to run the application and npm run build to build it.
For setting the API URL and key value , i have created .env.development and .env.qa for test and QA environment. But how to deploy this file in azure devops,like how to setup the environemtn variable in pipeline.
can someone guide me through steps.
We have a similar setup, multiple dotenv files for each environment. In the package.json, we've defined multiple build scripts:
"scripts": {
"build": "react-scripts build",
"build:test": "env-cmd --no-override .env.tst react-scripts build",
"build:qa": "env-cmd --no-override .env.qa react-scripts build",
"build:prod": "env-cmd --no-override .env.prod react-scripts build"
},
Don't use .env.production or .env.test however, otherwise, these will be used automatically by react-scripts in every build or test command.
I have successfully implemented the feature in Azure Devops.
I have created seperate zip file by creating new task for test and qa,buildid with the suffix mentioning the environment in the Build Pipeline. Similarly we need to mention the given zip folder name in Test and QA task in release pipeline.
npm run build creates production build of the project. How do I create development build? I'm using gradle-node-plugin to build the artifact. The project has standard create-react-app configuration.
This is not really doable with just create-react-app, there is an open issue Here and it doesn't look like it will be added anytime soon.
However, you can use a package called dotenv for that, following are the steps you should take:
Install dotenv (make sure to add save dev) npm install dotenv-cli --save-dev
In package.json scripts section add new script: "build:dev": "dotenv -e .env.development react-scripts build",
And you can build for development with npm run build:dev
PS: if you want to avoid mistakenly deploying dev builds to production (as mentioned here) you can add build:prod to package.json and disable the regular build command, see code:
"build:dev": "dotenv -e .env.development react-scripts build",
"build:prod": "dotenv -e .env.production react-scripts build",
"build": "echo \"Please use build:dev or build:prod \" && exit 1",
Also note that process.env.NODE_ENV will still be production but it'll load your .env.development file
Thanks, #Moses. This is an extension to the answer posted by Moses Schwartz. You can also make the build pick the environment files dynamically by exporting the value of the environment(development, test, production) in the bash shell. And then you don't have to have different build commands for different environments.
You can use this in your package.json
"start": "dotenv -e .env react-scripts start",
"build": "dotenv -e .env.${REACT_APP_ENVIRONMENT} react-scripts build",
So when your run npm start, it will pick the environment values from .env
and when you run npm run build, it will pick the environment values from .env.{REACT_APP_ENVIRONMENT}
To define the REACT_APP_ENVIRONMENT, you can do:
export REACT_APP_ENVIRONMENT="development" or
export REACT_APP_ENVIRONMENT="test" or
export REACT_APP_ENVIRONMENT="production"
Hope this helps. This will help in staging the react application for multiple environments.
Thanks to #Tx_monster comment
github.com/Nargonath/cra-build-watch
A script for create-react-app that writes development builds to the disk
npm install -D cra-build-watch
package.json:
{
"scripts": {
"watch": "cra-build-watch"
}
}
npm run watch
I need to build bundle-stats.json to work with webpack-bundle-analyzer.
Here how i'm trying build it , but it does not creating any file.
npm run build -- --stats
Could you please help me
The --stats flag was added back into CRA in this PR.
So you can use webpack-bundle-analyzer again.
stats have been remove from CRA see
It's recommended to use source-map-explorer
npm i -g source-map-explorer
source-map-explorer 'build/static/js/*.js'.
You can do it with #craco/craco which is a tool to use a custom webpack configuration with Create React App.
As explained on this article:
Install #craco/craco and webpack-bundle-analyzer
npm install #craco/craco webpack-bundle-analyzer --save-dev
Create a file named craco.config.js in the root of your project folder with this content:
const BundleAnalyzerPlugin =
require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
module.exports = function () {
return {
webpack: {
plugins: [new BundleAnalyzerPlugin({ analyzerMode: "server" })],
},
};
};
Add this "analyze" script to your package.json scripts sections:
{
...
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
+ "analyze": "craco build"
}
}
Now run:
npm run analyze
Because you set the analyzerMode to "server" in your craco config, you will automatically get your browser open with the results served as a webpage (you can use the "json" option if you want the output without involving the browser)
Firstly, add the webpack-bundle-analyzer to your dev dependecies:
yarn add -D webpack-bundle-analyzer
Then you can sequentially run commands:
yarn build -- --stats
yarn webpack-bundle-analyzer ./build/bundle-stats.json
Or, for your convenience, you can add the script to your package.json:
"scripts": {
...
"analyze": "yarn build -- --stats && yarn webpack-bundle-analyzer ./build/bundle-stats.json"
}
Instead of yarn you can use npm, just edit the command accordingly.
Then you can run the script using yarn analyze or the scripts runner UI available in VS Code like I do. You can also add a script for deleting the build folder if this already exists before creating a new one. For this, dependently on your platform, you can use the cmd or bash command:
cmd: if exist build\\ ( rmdir /s /q .\\build )
bash: [ -d 'build' ] && rm -r build
So the final solution will look like this:
"scripts": {
...
"analyze": "yarn remove_build && yarn build -- --stats && yarn webpack-bundle-analyzer ./build/bundle-stats.json",
"remove_build": "if exist build\\ ( rmdir /s /q .\\build )"
}
How to use .env in react . I can get access to .env.development and .env.production with
"start":"react-scripts start",
"build": "react-scripts build",
How to get access to another like .env.staging ?
I gave like this
"build_staging": "set REACT_APP_ENV=staging & react-scripts build",
but not working.
Any suggestions please.
To keep things consistent across linux(my production server) and windows(my development server) I use cross-env
npm install --save cross-env
and my scripts look like this
"scripts": {
"dev": "cross-env NODE_ENV=development node server",
"build": "cross-env NODE_ENV=production next build ",
"start": "cross-env NODE_ENV=production node server"
},
so to set a custom env like REACT_APP_ENV you'll need to
"build_staging": "cross-env REACT_APP_ENV=staging react-scripts build",
and you can access it in your javascript code using
process.env.REACT_APP_ENV
also to start a staging server you might want to add
"start_staging": "cross-env REACT_APP_ENV=staging react-scripts start"
more about this here
[CONTEXT]
- I've created React project with Create React.
- Running on Windows 10
- Using VSCode IDE
- I have the file .env.development on above /src folder.
- My code has console.log(process.NODE_ENV) and console.log(process.REACT_APP_YOUR_KEY)
[PROBLEM]
When I'm running the program with npm start, the browser prints 'development' for NODE_ENV, but for my React .env variable, it prints undefined.
I try to run npm start with changing the default script of package.json to this start script: set REACT_APP_YOUR_KEY && react-scripts start. Then there isn't any undefined, all works well. 🤨
[SOLUTION]
The cause was that the file .env.development is not detected correctly. My hypothesis is the environment development file, Windows or VSCode don't detect well.
Windows File Explorer files
VS Code explorer. Look up the icon of the files 🤔
You have to change the file name from .env.development to .env.
[SOLUTION]: I've created env.js as shown below.
env.js placement
after that i have added in index.html the script below
my env.js content
NB: i can acces my env.js var without import them (it seems the best way for me)