01 December 2024
Deploying a React app involves several steps to prepare the app for production, including optimizing the build, configuring deployment settings, and choosing a hosting platform. This note focuses on the preparation of a React app for production using the npm run build
command, which creates an optimized version of your app for deployment.
npm run build
When you’re ready to deploy your React app, the first step is to create a production build. React provides a command npm run build
that bundles your app into static files optimized for performance. This build includes minified JavaScript, optimized assets, and a structure that can be served by a static server.
Ensure the Project is Ready:
npm start
).Create a Production Build: To create a production-ready build, open your terminal and run:
npm run build
This command does the following:
After running the command, a new folder named build/
will be created in your project directory.
Inspect the Build Folder: The build/
folder will contain the following files:
index.html
: The main HTML file that includes links to your bundled JavaScript and CSS.static/
: A folder containing all the assets (images, fonts, etc.) and minified JavaScript and CSS files.asset-manifest.json
: Contains a list of files with their hash for cache management.This build folder is ready to be deployed to a static server.
Environment Variables: Ensure that all necessary environment variables are set for production. You can define them in .env
files or directly in the server environment.
For example, if you need to specify a different API URL for production, you can use:
REACT_APP_API_URL=https://api.yourdomain.com
These environment variables are automatically replaced during the build process.
Check the Build: It's a good idea to test the build locally before deploying. You can use a simple static server like serve to serve your production build.
First, install serve
globally if you don’t have it:
npm install -g serve
Then, run the following command to serve your build:
serve -s build
This will start a local server that serves your production build, allowing you to check if everything is working as expected before deploying it to a live server.
npm run build
build
command optimizes your React app for production by reducing the file sizes (through minification), removing unnecessary code, and making the app load faster.Once the build is ready, you can deploy it to your desired hosting platform. Some common platforms for deploying React apps include:
build/
folder or link your GitHub repository.npm run build
is the key command for preparing your React app for production. It bundles and optimizes your app for performance and scalability.build/
folder containing all the optimized assets ready to be deployed.By following these steps, you’ll ensure your React app is production-ready and performs optimally for end-users.