In this article, we will see how to deploy a react application GitHub pages.
This article assumes that you have a GitHub account, if not, create one here.
Creating the React App
Create a react app using the following command:
npx create-react-app deploy-github-pages
Now install the gh-pages
package as a development dependency.
This helps in deploying the React app to GitHub pages.
npm install gh-pages -D
Updating package.json
Open package.json
and add the following line:
"homepage": "https://<your_username>.github.io/<repo_name>"
Example:
"homepage": "https://collegewap.github.io/deploy-github-pages"
This will be the URL of your application when you deploy it.
Now add the following scripts to package.json
:
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
Here we have added 2 scripts, one is to build the project locally and another to upload the build files to GitHub pages.
This is how the package.json
would look now:
{
"name": "deploy-github-pages",
"version": "0.1.0",
"homepage": "https://collegewap.github.io/deploy-github-pages",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": ["react-app", "react-app/jest"]
},
"browserslist": {
"production": [">0.2%", "not dead", "not op_mini all"],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"gh-pages": "^4.0.0"
}
}
Pushing the code to GitHub
Create a public repository named deploy-github-pages
in GitHub.
If you want to deploy a private GitHub repository to GitHub pages, then you will have to upgrade your account.
Now add the files and commit the changes in your project:
git add *
git commit -m "Adding GitHub Pages"
Now add and push the code to the remote repository:
git remote add origin https://github.com/<username>/<repo_name>.git
# git remote add origin https://github.com/collegewap/deploy-github-pages.git
git push -u origin master # or main
Deploying to GitHub pages
Run the following command inside the project:
npm run deploy
Now it will create a branch called gh-pages
and push it to the remote repository.
Now open your GitHub repository and click on Settings:
In Settings, choose Pages
.
In the Build and deployment section,
- Choose source as Deploy from branch.
- Branch as
gh-pages
. - Folder as
/(root)
. - Click on Save.
Again run the deploy command inside your project:
npm run deploy
Now your React application will be deployed to GitHub pages.
Top comments (0)