Setup Development and Production Environment for React App
Building a web application using React, requires some environment configuration for successful React development. Setting up an environment in terms of configuring code bundler, JavaScript transpiler, linter, testing library, and third-party plugin dependency, etc.
When developing a React web application, developers can only use two environments by default.
- Development and
- Production
There might be other multiple environment support for a single project, with Development and Production environments for example Staging, Testing, etc. having a separate environment that mimics the production version can really help with testing code changes before they go live.
In this tutorial, we are setting up a development and production environment for React. If you are new to react and don’t know much about webpack then you can use React Create React App. It’s a comfortable environment for learning React and is the best way to start building a new single-page application in React.
For configuration, we are using React 17, Webpack 5, and the Babel 7 version.
let’s start!!!!
Stpe 1: Create a directory called
react-setup
and inside directory runnpm init --yes
. It will simply generate an empty npm project without going through an interactive process.
Step 2: Let’s add react and webpack in our project. Run the below command to install react and webpack.
npm install react react-dom webpack webpack-cli webpack-dev-server webpack-merge --save
Let’s look at packages one by one which we installed using the above command.
- react: React is a JavaScript library for creating user interfaces.
- react-dom: serves as the entry point to the DOM and server renderers for React.
- webpack: webpack is an open-source JavaScript module bundler. It is made primarily for JavaScript, but it can transform front-end assets such as HTML, CSS, and images if the corresponding loaders are included. webpack takes modules with dependencies and generates static assets representing those modules.
- webpack-cli: It’s a tool used to run webpack on the command line.
- webpack-dev-server: It is a web server based on express. Use webpack with a development server that provides live reloading. This should be used for development only.
- webpack-merge: It provides a merge function that concatenates arrays and merges objects creating a new object. We are using this package in our webpack configuration file.
Step 3: Install babel packages. run below command to install babel packages.
npm install @babel/core @babel/preset-env @babel/preset-react -D
Below is the summary of the installed babel packages:-
- Babel: Babel is a JavaScript compiler. it is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backward-compatible version of JavaScript in current and older browsers or environments.
- @babel/core: It allows transpiling JavaScript files using Babel and webpack.
- @babel/preset-env: It is a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms are needed by your target environment(s).
- @babel/preset-react: convert JSX syntax. JSX stands for JavaScript XML. JSX allows us to write HTML in React.
Step 4: Let’s install remaning packages require for react setup.run below command.
npm install babel-loader css-loader style-loader html-webpack-plugin mini-css-extract-plugin react-router-dom -D
Below is the summary of the installed package:-
- babel-loader: package allows transpiling JavaScript files using Babel and webpack.
- css-loader: It’s loader that can parse a CSS file and apply various transforms to it.
- style-loader: It injects CSS into the DOM using multiple <style></style> and works faster. Recommended to use only in development mode.
- html-webpack-plugin: simplifies the creation of HTML files to serve your webpack bundles.
- mini-CSS-extract-plugin: It is more often used in production mode to get separate CSS files.
- react-router-dom: This allows us to build a single-page web application with navigation without the page refreshing as the user navigates.
Step 5: Now we are done with basic package installation required for react. let’s start with configuration part. create babel.config,json file and paste below code.
Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backward-compatible version of JavaScript. It will run certain transformations / plugins on a subset of files /directories. You can learn more about babel here.
Below is the babel.config.json file.
Step 6: Create directory config and inside this directory create webpack.config.js, webpack.dev.config.js and webpack.prod.config.js files and paste below code to specific file.
A configuration file in Webpack is basically a common.js module. The config file is a place to put all of your configuration, loaders, and other specific information relating to your build.
- entry: The entry object is where webpack looks to start building the bundle.
- output: how and where it should output your bundles, assets, and anything else you bundle or load with webpack. Asset Modules is a type of module that allows one to use asset files (fonts, icons, etc) without configuring additional loaders and as of webpack 5, using the built-in Asset Modules, no need to externally add file-loader, url-loader and raw-loader now. assetModuleFilename generates all the image assets inside the images directory inside the dist directory. you can skip this, by default it will generate all the image assets inside the dist directory.
- module: webpack only understands JavaScript and JSON files. Loaders allow webpack to process other types of files and convert them into valid modules.
At a high level, loaders have two properties in your webpack configuration:
- The test property identifies which file or files should be transformed.
- The use property indicates which loader should be used to do the transforming.
- plugins: Plugins work at bundle or chunk level and usually work at the end of the bundle generation process. Plugins can also modify how the bundles themselves are created.
- publicPath: This allows you to specify the base path for all the assets within your application.
- historyAPIFallback: will redirect 404s to /index.html. While using browser router on page reload on browser give 404, to prevent this issue historyAPIFallback property use.
You can learn more about webpack configuration properties here. If you are new to webpack then look at this beginner webpack config guide.
Step 7: We are done with configuration, now let’s write some react code.create directory src and inside src directory create index.jsx, index.html, App.jsx, Home.jsx and Login .jsx files and paste below code.
index.jsx
import React from “react”;
import ReactDOM from “react-dom”;
import App from “./App”;import “../styles/style.css”;ReactDOM.render(<App />, document.getElementById(“app”));
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>React</title>
</head>
<body class="container-fluid">
<div id="app"></div>
</body>
</html>
App.jsx
import React, { Suspense, lazy } from "react";
import { BrowserRouter as Router, Route, Switch, Link } from "react-router-dom";const HomeComp = lazy(() => import("./Home"));
const LoginComp = lazy(() => import("./Login"));function App() {
return (
<Router>
<Link to="/">Home</Link><br />
<Link to="/login">Login</Link>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/" component={HomeComp} />
<Route exact path="/login" component={LoginComp} />
</Switch>
</Suspense>
</Router>
);
}
export default App;
Home.jsx
import React from "react";
import logo from "../images/react-logo.png";function Home() {
return (
<div>
<img src={logo} height="100" />
<h1>Welcome to React</h1></div>
);
}
export default Home;
Login.jsx
import React from "react";function Login() {
return (
<h2>Login Page</h2>
);
}
export default Login;
Step 8: Now create styles direactory and inside that create style.css file and paste below code also create images directory and inside that directory add any image with name react-logo.png
style.css
h1 {
color: blue;
}h2 {
color: red;
}
Finally, we are done with all the configuration and code changes. our project structure looks like this:
Step 9: let’s run our code. open package.json file and add below code inside script section.
"scripts": {
"start": "webpack serve --config ./config/webpack.dev.config.js",
"build": "webpack --config ./config/webpack.prod.config.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
Step 10: Now open terminal and go to our project directory and run below command :
npm start
After running the above command, on the terminal, we can see Compiled successfully message.
Now open the browser and paste the below URL into the address bar.
http://localhost:8888/
Now click on the Login anchor tag, it will navigate to the Login page.
Thank you for reading. Happy Coding!!!!
- Automate Deep Learning (YOLO) training on AWS using Spotty check out this awesome article by Khushbu Adav.
- Learn docker-compose operations using Makefile, check out this amazing article by Khushbu Adav.
- Want to become an AWS Certified but worried about where to start? How to start? checkout this amazing article by Milind Karandikar.