Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and run a development build of an application using create-react-app configuration

Tags:

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.

like image 304
Tuomas Toivonen Avatar asked Oct 23 '19 07:10

Tuomas Toivonen


2 Answers

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

like image 109
Moses Schwartz Avatar answered Sep 23 '22 00:09

Moses Schwartz


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.

like image 20
Harpreet Singh Avatar answered Sep 26 '22 00:09

Harpreet Singh