How To Have Angular Environment Structure in React Applications Without CRA
If you have an experience with Angular you are familiar with the environment structure in this project I think it’s so cool to have a different environment value in development and production mode in React applications so I decide to use this structure in React applications. Let’s start to implement it :
👋 Initial Step
to achieve this task we need to access to Webpack files to change and add new tasks so if you use CRA (Create React App) you have to find a way to change Webpack tasks or You Can Make Your Webpack Tasks By Yourself Own.
🤔 What Should We Do
First We Need To Add environment
folder to the root of our projects, after that we have to create a separate file for each mode of production
and development
with a name like this environment.prod.ts
and environment.ts
. we use environment.ts
in development
mode.
after creating files we have to add a new task to webpack build files and handle the switching between these two files.
💻 Coding Time
now as first step to adding this task we have to install file-replace-loader
this package will help us to replace import path during the build, after install this package with this command:
$ yarn add -D file-replace-loader
or if you use npm
as package manager you have to run this:
$ npm install file-replace-loader
now we are ready to add webpack task. now in your webpack build file you have to add the below task in ruls
sections like this:
in this rules we are looking for environment.ts
file and we replace it with environment.prod.ts
so after the build was finished your application will use the production environment and you don’t need to change anything else. in this way you can have separate value for each environment variables and develop your applications easier than ago.
and I will be appreciate if you check this link below too:
❤ I hope this article is help you to develop better. ❤