Deploying React App on Apache server
In order to host React app on apache server, we will first make bundle of our React app and then upload that to the server which will run.
So following are the steps for this-
Step 1: Create app from create-react-app command
create sample project from the following command-
npm create-react-app first_app
Step 2: Install gulp packages
execute following command to install gulp packages as a dev-dependancies.
npm install — save-dev gulp gulp-inline-source gulp-replace
Step 3: Create .env file
Now create a file named .env in project root folder and write following environment variables in it.
INLINE_RUNTIME_CHUNK=false
GENERATE_SOURCEMAP=false
SKIP_PREFLIGHT_CHECK=true
Step 4: Create gulpfile.js file in root folder
Now create a file named gulpfile.js in project root folder with following code-
const gulp = require(‘gulp’)
const inlinesource = require(‘gulp-inline-source’)
const replace = require(‘gulp-replace’)gulp.task(‘default’, () => {
return gulp.src(‘./build/*.html’)
.pipe(replace(‘.js”></script>’, ‘.js” inline></script>’))
.pipe(replace(‘rel=”stylesheet”>’, ‘rel=”stylesheet” inline>’))
.pipe(inlinesource({
compress: false,
ignore: [‘png’]
}))
.pipe(gulp.dest(‘./build’))
});
Step 5: Mention domain/subdomain in package.json
Mention domain or subdomain name in homepage key of package.json file like below-
“homepage”: “http://www.mydomain.com"
OR
“homepage”: “http://www.mydomain.com/test"
Step 6: Create .htaccess file
Create .htaccess file in public folder with following content-
FallbackResource ./index.html
Step 7: Mention basename in routing
If your project has routing then mention subdomain name as basename prop in router.
<BrowserRouter basename={“/test”}>
OR
<Router basename={“/test”}>
Step 8: Make build
Execute build command to make its bundle.
npm run build
OR
npx react-scripts build
Step 9: Execute gulp command
Now execute following command to bundle all the JS and CSS files in the static build folder into the single main html file.
npx gulp
Step 10: Deploy the files
Now there will be a folder created named build. Upload the content of this folder to the subdomain or domain through filezilla.
Now access the url and react app should work!!!