Как развернуть React приложение онлайн и бесплатно


Lead Front-end Developer в Temy, Преподаватель Компьютерной школы Hillel.
React в свое время привел к революционным изменениям в разработке веб-сайтов.
Стало довольно легко сделать хороший интерактивный веб-сайт. Но у новичков часто возникает вопрос — как сделать так, чтобы мой сайт могли увидеть другие пользователи в интернете. Конечно, можно купить платный хостинг и развернуть приложение там. Но не торопитесь тратить деньги — развернуть React приложение можно и совершенно бесплатно.
React приложение в своем финальном состоянии действительно представляет собой статический веб-сайт. Статичным называется сайт, содержащий только статические файлы: такие как HTML, JS, CSS и картинки.
Чтобы получить этот статический сайт, нужно выполнить команду npm run build. После этого мы получим папку build, в которой будут собраны все файлы, необходимые для работы нашего статического сайта. Основным файлом является index.html. Дело в том, что большинство веб-серверов настроены так, что когда мы открываем какой-нибудь URL в браузере, то веб-сервер ищет по указанному адресу файл index.html или index.htm. Если веб-сайт динамичен, то веб-сервер может быть сконфигурирован для поиска файлов типа index.php, index.apsx и т.д.
Попробуйте открыть следующие ссылки:
Вы увидите одинаковые страницы сайта.
Все это необходимо для понимания, что в статическом сайте в папке должен быть файл index.html, который будет отдаваться веб-сервером.
В случае SPA (Single Page Application), которым является наше React приложение, этот файл обычно имеет пустое тело только с одним элементом, в который монтируется JavaScript приложение, основной код которого хранится в JS файле, который обычно называется bundle.
Итак, когда мы получили папку build, эта папка является нашим статическим веб-сайтом. Остается только найти веб-сервер, который может хостить статические веб-сайты.
На самом деле таких серверов и сервисов очень много, причем и хостинг-провайдері, предоставляющих бесплатный хостинг, и сервисы типа Heroku, Amazon S3, Firebase и т.д.
Мы рассмотрим два наиболее популярных сервиса в Front-end сообществе — GitHub Pages и Netlity.
GitHub Pages
Думаю, даже большинство начинающих уже знают, что такое GitHub и как им пользоваться. Но немногие разработчики знают о дополнительном сервисе, GitHub Pages.
GitHub Pages позволяет развернуть статический сайт прямо в GitHub, получить доменный адрес и даже при необходимости подключить свой собственный домен. Так как React приложение — это также статический сайт, то его также можно здесь хостить.
Есть несколько способов развернуть свое React приложение на GitHub Pages.
Основные способы это:
- В отдельной бранче или в специальной папке (например, docs) основной бранчи. Об этом способах вы можете прочитать в документации GitHub Pages.
- Мой любимый автоматический способ — используя npm пакет gh-pages.
Сначала его нужно установить:
npm install gh-pages -D
Затем в scripts вашего package.json файла добавьте следующие скрипты:
"predeploy": "npm run build", "deploy": "gh-pages -d build",
Затем сохраните изменения и закомтите их. Вы сможете разворачивать React приложение одной командой:
npm run deploy
Эта команда сама сделает билд (build) вашего React приложения и, если нет никаких ошибок, то создаст (или обновит) дополнительную ветвь gh-pages и закомитит туда последнюю версию сборки вашего приложения.
Страница приложения будет доступна по адресу.
Например, я когда-то деплоил простенькое приложение для изучения английских слов, фраз и условных выражений на GitHub Pages и вот какой адрес имеет веб-приложение: https://sergii-zhuravel.github.io/learning-cards/
Netlify
Netlify — это сервис, который автоматизирует сборку, развертывание и управление статическими веб-сайтами. Это одно из самых быстрых и простых развертываний на сегодняшний день.
Netlify предлагает бесплатный тариф, поэтому попробовать его может любой желающий. Его даже стартапы используют как, например, тестовую среду. Войти в Netlify также очень просто, можно использовать любой из параметров (Github, Gitlab, Bitbucket, Email), указанных на странице входа.
Существует несколько способов развернуть наше веб-приложение Netlify.
Несколько основных вариантов:
- Перетащите папку build в веб-интерфейс сервиса Netlify
- Используя netlify-cli инструмент (https://www.npmjs.com/package/netlify-cli)
- Импортировать проект из GitHub (или другого Git репозитория)
Импортировать проект из GitHub очень просто. Для этого нужно нажать кнопку «Import from Git» и следовать инструкциям.
Но пожалуй самый быстрый и простой вариант — это метод «перетащи и отпусти». Для этого нужно лишь сбилдить React приложение (npm run build) и перетащить папку build в специальную область на странице Netlify (с надписью «Drag and drop your site output folder here»).
Как мы видим, развернуть React приложение можно быстро, легко и бесплатно. Кстати, Netlify имеет также сервис Netlify CMS, являющийся headless CMS, и может выступать бекендом для вашего React приложения с возможностью администрировать контент.
Это очень крутая и популярная штука. Но это уже другая история:)
Рекомендуем курс по теме
Front-end Pro advanced

Lead Front-end Developer в Temy, Преподаватель Компьютерной школы Hillel.
Deploy React App github pages с собственными настройками Webpack
Всем доброго времени суток! У меня есть готовое React-приложение. Настройку Webpack производил самостоятельно, то бишь не пользовался стандартом create-react-app, где, говорят, deploy github pages работает идеально. По бороздил интернет поисках ответа и кое что нарыл. Свое приложение на githab pages я запускаю, но с некоторыми багами, которые не могу никак понять. Теперь по порядку: я писал приложение созданного на github и комитил туда изменения пока не закончил. То есть локально и удаленно оно связано. Когда закончил установил npm i gh-pages -DE. И прописал настройки в package.json:
Webpack.config и структура проекта выглядит таким образом:
Далее прописал npm run deploy, он собрал bundle.js и ответил что gh-pages — Published. Но ссылку в консоле не была указана, где по материалам изучения у всех она была. Я двинулся дальше. Внес изменения npm add . , закомитил npm commit -m ‘add’ , из запушил npm push original master. В github настройках проекта и увидел что gh-pages залетел.
Нажимаю на ссылку, проект открывается. Но не так как надо. У меня в приложении есть 404 route страница, где есть ссылка на главную route страницу с path=»/».
Я нажимаю туда, а в адресной строке вот такая абракадабра
Если нажать ctrl+F5, то страница будет не найдена. И еще есть проблема с тегами img. У них есть, допустим у одного, src=»../img/logo.svg». И он не отображается, хотя в css стилях есть такое и оно почему то отображается.
Я даже не знаю в чем беда, и вот еще index.html 
Отслеживать
1,865 1 1 золотой знак 17 17 серебряных знаков 25 25 бронзовых знаков
задан 15 авг 2020 в 9:02
Алексей Штрих Алексей Штрих
TL;DR
Если вы хотите опубликовать пользовательскую страничку (https://.github.io) на github pages , но вам важно, чтобы:
• исходный код был в том же репозитории
• ваш сайт открывался из корневой директории, а не подпапки
Тогда
• необходимо создать отдельную ветку, которая будет хранить в себе исходный код проекта
• настроить деплой
В итоге
В гите будет 2 ветки (dev и master), ветка dev будет хранить исходный код, а ветка master будет по сути build папкой из которой будет хоститься сайт.
В начале года, я пообещала себе наконец сделать свой сайт-визитку. Успешно добравшись до этапа деплоя на github pages, я хотела облегченно выдохнуть — всего 5 простых шагов отделяли меня от собственной странички в Интернете. Как оказалось это было только начало.
Меня интересовала возможность хостинга своей страницы как пользовательской (https://.github.io). Однако, мне хотелось держать исходный код проекта в том же репозитории, откуда он деплоится.
Основная проблема заключалась в том, что git позволяет деплоить пользовательские странички только из дефолтной ветки (master), а также не дает возможности указать кастомную папку в качестве корневой директории для деплоя.
Быстрый гуглинг не дал результатов. В основном предлагалось:
• задеплоить сайт как проект (хочу красивый урл )
• держать в репозитории только готовый билд (а исходники-то куда )
• вынести исходный код в submodules (ну зачем так сложнооо )
Подумав еще какое-то время и почти решившись на вариант с submodules, я наткнулась на пошаговое описание деплоя реактивного приложения на github pages. В одном из шагов предлагалось явно указать ветку, в которую будет пушится билд.
Бинго: можно ведь сложить исходники в отдельную ветку, а master держать в качестве ветки с готовой сборкой ️ ♀
Итог здесь, а я надеюсь, что этот способ позволит кому-то сберечь пару часов и с десяток нервных клеток
Saved searches
Use saved searches to filter your results more quickly
Cancel Create saved search
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Deploying a React App (created using create-react-app) to GitHub Pages
gitname/react-gh-pages
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Switch branches/tags
Branches Tags
Could not load branches
Nothing to show
Could not load tags
Nothing to show
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Cancel Create
- Local
- Codespaces
HTTPS GitHub CLI
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more about the CLI.
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
efb2192 Jul 19, 2023
….3.1 Bump semver from 6.3.0 to 6.3.1
Git stats
Files
Failed to load latest commit information.
Latest commit message
Commit time
June 18, 2023 13:35
January 19, 2022 19:54
January 19, 2022 19:54
November 27, 2022 15:48
February 3, 2023 14:41
July 19, 2023 08:34
January 19, 2022 19:54
January 19, 2022 19:54
README.md
Deploying a React App* to GitHub Pages
* created using create-react-app
Introduction
In this tutorial, I’ll show you how you can create a React app and deploy it to GitHub Pages.
To create the React app, I’ll be using create-react-app , which is a tool people can use to create a React app from scratch. To deploy the React app, I’ll be using gh-pages , which is an npm package people can use to deploy things to GitHub Pages, a free web hosting service provided by GitHub.
If you follow along with this tutorial, you’ll end up with a new React app—hosted on GitHub Pages—which you can then customize.
Tutorial
Prerequisites
- Node and npm are installed. Here are the versions I’ll be using while making this tutorial:
$ node --version v16.13.2 $ npm --version 8.1.2
Installing npm adds two commands to the system— npm and npx —both of which I’ll be using while making this tutorial.
$ git --version git version 2.29.1.windows.1
Procedure
1. Create an empty repository on GitHub
- Sign into your GitHub account.
- Visit the Create a new repository form.
- Fill in the form as follows:
- Repository name: You can enter any name you want*.
* For a project site, you can enter any name you want. For a user site, GitHub requires that the repository’s name have the following format: .github.io (e.g. gitname.github.io )
The name you enter will show up in a few places: (a) in references to the repository throughout GitHub, (b) in the URL of the repository, and (c) in the URL of the deployed React app.
In this tutorial, I’ll be deploying the React app as a project site.
* For GitHub Free users, the only type of repository that can be used with GitHub Pages is Public. For GitHub Pro users (and other paying users), both Public and Private repositories can be used with GitHub Pages.
That will make it so GitHub creates an empty repository, instead of pre-populating the repository with a README.md , .gitignore , and/or LICENSE file.
At this point, your GitHub account contains an empty repository, having the name and privacy type that you specified.
2. Create a React app
- Create a React app named my-app :
In case you want to use a different name from my-app (e.g. web-ui ), you can accomplish that by replacing all occurrences of my-app in this tutorial, with that other name (i.e. my-app —> web-ui ).
$ npx create-react-app my-app
That command will create a React app written in JavaScript. To create one written in TypeScript, you can issue this command instead:
$ npx create-react-app my-app --template typescript
That command will create a new folder named my-app , which will contain the source code of a React app.
In addition to containing the source code of the React app, that folder is also a Git repository. That characteristic of the folder will come into play in Step 6.
Branch names: master vs. main
The Git repository will have one branch, which will be named either (a) master , the default for a fresh Git installation; or (b) the value of the Git configuration variable, init.defaultBranch , if your computer is running Git version 2.28 or later and you have set that variable in your Git configuration (e.g. via $ git config —global init.defaultBranch main ). Since I have not set that variable in my Git installation, the branch in my repository will be named master . In case the branch in your repository has a different name (which you can check by running $ git branch ), such as main ; you can replace all occurrences of master throughout the remainder of this tutorial, with that other name (e.g. master → main ).
$ cd my-app
At this point, there is a React app on your computer and you are in the folder that contains its source code. All of the remaining commands shown in this tutorial can be run from that folder.
3. Install the gh-pages npm package
- Install the gh-pages npm package and designate it as a development dependency:
$ npm install gh-pages --save-dev
At this point, the gh-pages npm package is installed on your computer and the React app’s dependence upon it is documented in the React app’s package.json file.
4. Add a homepage property to the package.json file
- Open the package.json file in a text editor.
$ vi package.json
In this tutorial, the text editor I’ll be using is vi. You can use any text editor you want; for example, Visual Studio Code.
* For a project site, that’s the format. For a user site, the format is: https://.github.io . You can read more about the homepage property in the «GitHub Pages» section of the create-react-app documentation.
< "name": "my-app", "version": "0.1.0", + "homepage": "https://gitname.github.io/react-gh-pages", "private": true,
At this point, the React app’s package.json file includes a property named homepage .
5. Add deployment scripts to the package.json file
- Open the package.json file in a text editor (if it isn’t already open in one).
$ vi package.json
"scripts": < + "predeploy": "npm run build", + "deploy": "gh-pages -d build", "start": "react-scripts start", "build": "react-scripts build",
At this point, the React app’s package.json file includes deployment scripts.
6. Add a «remote» that points to the GitHub repository
- Add a «remote» to the local Git repository. You can do that by issuing a command in this format:
$ git remote add origin https://github.com//.git
To customize that command for your situation, replace
$ git remote add origin https://github.com/gitname/react-gh-pages.git
That command tells Git where I want it to push things whenever I—or the gh-pages npm package acting on my behalf—issue the $ git push command from within this local Git repository.
At this point, the local repository has a «remote» whose URL points to the GitHub repository you created in Step 1.
7. Push the React app to the GitHub repository
- Push the React app to the GitHub repository
$ npm run deploy
That will cause the predeploy and deploy scripts defined in package.json to run. Under the hood, the predeploy script will build a distributable version of the React app and store it in a folder named build . Then, the deploy script will push the contents of that folder to a new commit on the gh-pages branch of the GitHub repository, creating that branch if it doesn’t already exist.
By default, the new commit on the gh-pages branch will have a commit message of «Updates». You can specify a custom commit message via the -m option, like this:
$ npm run deploy -- -m "Deploy React app to GitHub Pages"
At this point, the GitHub repository contains a branch named gh-pages , which contains the files that make up the distributable version of the React app. However, we haven’t configured GitHub Pages to serve those files yet.
8. Configure GitHub Pages
- Navigate to the GitHub Pages settings page
- In your web browser, navigate to the GitHub repository
- Above the code browser, click on the tab labeled «Settings»
- In the sidebar, in the «Code and automation» section, click on «Pages»
- Source: Deploy from a branch
- Branch:
- Branch: gh-pages
- Folder: / (root)
That’s it! The React app has been deployed to GitHub Pages!
At this point, the React app is accessible to anyone who visits the homepage URL you specified in Step 4. For example, the React app I deployed is accessible at https://gitname.github.io/react-gh-pages.
9. (Optional) Store the React app’s source code on GitHub
In a previous step, the gh-pages npm package pushed the distributable version of the React app to a branch named gh-pages in the GitHub repository. However, the source code of the React app is not yet stored on GitHub.
In this step, I’ll show you how you can store the source code of the React app on GitHub.
-
Commit the changes you made while you were following this tutorial, to the master branch of the local Git repository; then, push that branch up to the master branch of the GitHub repository.
$ git add . $ git commit -m "Configure React app for deployment to GitHub Pages" $ git push origin master
I recommend exploring the GitHub repository at this point. It will have two branches: master and gh-pages . The master branch will contain the React app’s source code, while the gh-pages branch will contain the distributable version of the React app.
References
- The official create-react-app deployment guide
- GitHub blog: Build and deploy GitHub Pages from any branch
- Preserving the CNAME file when using a custom domain
Notes
- Special thanks to GitHub (the company) for providing us with the GitHub Pages hosting service for free.
- And now, time to turn the default React app generated by create-react-app into something unique!
- This repository consists of two branches:
- master — the source code of the React app
- gh-pages — the React app built from that source code
Contributors
Thanks to these people for contributing to the maintenance of this tutorial.
This list is maintained manually—for now—and includes (a) each person who submitted a pull request that was eventually merged into master , and (b) each person who contributed in a different way (e.g. providing constructive feedback) and who approved of me including them in this list.
About
Deploying a React App (created using create-react-app) to GitHub Pages