react приложение на github pages

Deploying React Applications to Github Pages

1*ocyPCQ5F lWR3EeO5ai2Hw

1*5ybVj54fnQOms TmENQArA

Well, it’s simpler than you might think, in this article I’ll be showing you how to deploy your react applications to gh-pages in no time.

This tutorial assumes that you have some sort of knowledge on how to use react and git.

For this tutorial, I’ve created a simple app, it’s a react application that contains an editable and non-editable text input sharing the same state. Anything the user puts in the editable field is been displayed in the output (nothing too fancy)d

I have created this using create-react-app.

1*KMgzubgGnDvmpLDHY84ogA

Now follow these steps to publish your react application on gh-pages :

npm install gh-pages or yarn add gh-pages

This package would help us to create a gh-pages branch on Github and also serve our bundled react files on the branch.

3. Locate the package.json file in your root directory, add this line of code to your script: «homepage»: «link-to-your-repository», and save. In my own case it would look like this:

Note: If you are linking your domain name to your Github pages, this line would be a little different, it should be: «homepage»: «your-custom-domain»

4. In your package.json file, locate “scripts” add these lines of code:

So your «scripts» should look like this:

The predeploy command helps bundle the react app whilst the deploy command fires up the bundled file.

Thanks for reading and I do hope you found this article somewhat helpful.

Источник

Русские Блоги

Разверните свой проект React в онлайн-среде с помощью Github Page

введение

Позвольте мне сегодня объяснить, как использовать страницу github для развертывания вашего интерфейсного проекта.

1. Убедитесь, что ваш проект React запущен и работает

Попробуйте скомпилировать и запустить проект локально, чтобы проверить, нормально ли это

2. Создайте новый склад на github

Обратите внимание, что это новый общий склад. Вам не нужно создавать склад типа github.io. Если вы не знаете склад типа github.io, вы можете понять его по Baidu. Вот расширенный обзорный столбец Flutter, созданный автором с использованием github.io + hexo Для вашей справкиФлаттер Расширенный Тур。

Например, мой недавно созданный репозиторий github с именем jwc выглядит следующим образом:
553d867863ab2710e0c1a72a3a7ade50

3. Синхронизируйте локальный код с хранилищем github.

Этот шаг не является специфическим, читатель может git add. Git commit push и другие связанные операции, чтобы загрузить свой локальный код в хранилище.

4. Измените файл package.json локального проекта React.

1. Настройте домашнюю страницу:
Здесь вам нужно немного изменить адрес своего хранилища на github, например, мой https://github.com/ydjw/jwc
«homepage»: «https://ydjw.github.io/jwc»,
Здесь вам нужно немного изменить адрес своего репозитория github, например мой https://github.com/ydjw/jwc изменить в https://ydjw.github.io/jwc

2. Настройте параметры публикации

remaploy: предварительно скомпилируйте ваш проект в статический файл и поместите его в папку сборки
deploy: используйте gh-pages для развертывания содержимого вашей папки сборки.

5. Установите GH-страниц
6. Разверните проект на странице github.

После настройки откройте хранилище на github, вы обнаружите, что в исходном проекте есть дополнительная ветка gh-pages, в которой хранятся статические файлы после того, как мы упаковали и скомпилировали.
f7f6a6928a5f5ff004fd265165ddaf21

Переключитесь на настройку, мы видим, что проект был успешно развернут наhttps://ydjw.github.io/jwc/Получил.
be1ebe98d5f7e0c182100381a5a2088e

Источник

How to Deploy React Apps for Free With GitHub Pages

A step by step guide to hosting your React apps for free with GitHub Pages.

Join the DZone community and get the full member experience.

GitHub Pages has emerged as an excellent way for developers to deploy their projects online for free. It’s fast, free, and pretty simple, as it lets you host static websites directly from your GitHub repositories.

13699492 blogimg

Getting Started

In this tutorial, I’ll take you through all the steps involved in hosting a React App on GitHub pages.

Prerequisites:

Set Up React App

For the simplicity of this tutorial, we’ll be using create-react-app to set up our react project. Run the following command in the terminal to get your react app set up:

13699493 screenshot 158

Initialize Git Repository

Go to GitHub and create a repository for your react app. Once you’ve created the repository, run the following commands from the directory where you created your react app.

Create-react-app automatically initializes a git repository for you in the root app directory and makes the first commit. All you have to do is set up the remote to your GitHub repo and push the master branch. Remember to replace username with your own GitHub username while adding the origin remote.

Configure gh-pages

We now need to configure gh-pages to prepare our app for deployment.

Open the package.json file in your React application and add the following properties:

Your package.json file should look something like this now:

13699494 screenshot 153

Voila! Your app is now ready to deploy.

Deployment

Run the following command to deploy your app: npm run deploy

13699495 screenshot 155

As you can see, the deploy script first invokes the predeploy script, which creates a build directory with a production build of our app, which is then published by the deploy script.

The deploy script will create a branch names gh-pages which will host your app, and the app will be deployed at the link specified for the homepage field in your package.json file.

You will see the following message when you scroll down to the GitHub pages section of your app’s GitHub repo settings:

13699496 screenshot 157

App successfully deploy! This brings us to the end of this tutorial. You can find the example code in my GitHub repository.

Deploying Changes (optional)

You might be wondering that what would be the steps to make changes in our current app and deploy those changes to the hosted app. It’s as easy as it gets! First, simply commit your changes and push the master branch to Github using the following commands:

Источник

How to Deploy a Routed React App to GitHub Pages

602aaa1e0a2838549dcc5c67

When we build projects, we want to showcase them online. Instead of buying a domain and taking the time to configure it, it’s easier just to host it using GitHub Pages.

A project that just uses JavaScript, HTML and CSS is simple to host on GitHub Pages. Projects that are built in React, Vue or Angular require some configurations, though. This gives anyone who visits your application online the same experience you have when you build the application locally.

In this article, I’ll show you how to create a simple React application that uses routing and then we’ll learn how to upload it to GitHub Pages. We will give special attention to the routing part since it is important to understand and implement.

⚠️ This article assumes you have some knowledge of React and Git.

Prerequisites

You need to have Node, yarn and npm installed on your machine. To check if they are installed, open up a terminal window and type the following:

If these commands print out a version number in the terminal, you are good to go. If not, you need to go ahead and install what is missing.

We will also need to create a repository on GitHub. Head over to your account and create a new repository. Choose whichever name you deem fit for this project, but I will go with starter-project for the rest of this article.

To create our project, we will be using create-react-app. It is a package that lets you create a single page application with ease. To create a project, you need to type the following in the terminal:

Once the operation finishes, you will have a boilerplate React project, ready to go. To see if it works properly, head into the directory of the project (in our example it would be starter-project) and run the command:

If everything runs properly, you will see a message in the terminal that says that your application is running on a local server at this address: http://localhost:3000

If you head over there in your browser, you will see this:

IB8uRE3cjN

How to Deploy Your Project to GitHub

You may have noticed that we have not created any repository in GitHub. So before we move on, we must have our project uploaded there. Head over to your GitHub account and create a repository with the same name as the React project.

☝️ Make sure to mark your repository as public. If you mark it as private, you won’t be able to use GitHub Pages.

We are going to add this repository as a remote to our project. To do that, in the terminal, type:

So, in our case, the command looks like this:

It’s important to call the remote origin as it will be used in our deploy process.

After executing the command above, we can’t push our code yet. First, we need to configure an upstream branch and set the remote as origin.

Now, we can push all our project’s files to our repository.

In order for us to be able to upload our built application to GitHub Pages, we first need to install the gh-pages package.

This package will help us to deploy our code to the gh-pages branch which will be used to host our application on GitHub Pages.

To allow us to use the gh-pages package properly, we need to add two keys to our scripts value in the package.json file:

Next, we need to modify our package.json file by adding the homepage field. This field is used by React to figure out the root URL in the built HTML file. In it, we will put the URL of our GitHub repository.

To deploy our application, type the following in the terminal:

Running the command above takes care of building your application and pushing it to a branch called gh-pages, which GitHub uses to link with GitHub Pages.

? If you did not name your remote origin, you will get an error during this phase stating that: Failed to get remote.origin.url (task must either be run in a git repository with a configured origin remote or must be configured with the «repo» option).

You will know that the process was successful if at the end of it you see the word Published. We can now head to our GitHub repository under Settings and scroll down to the GitHub Pages section.

chrome egdTtIso1X

If you see a message similar to the one above, it means your application is now hosted successfully on GitHub Pages.

image 308Photo by Noah Glynn / Unsplash

Routing in React

But since the purpose of this article is to show a more complex application than the one we initially created, we will be discussing routing.

One component that is missing from out application is navigation. Our application won’t just be one page, it will probably have many pages. So, how will users be able to navigate between them?

Routing is the practice of selecting a path for traffic in a network. Or in more basic terms, what happens when you click on a link inside of a webpage and where you get redirected.

React is a library, and it does not contain everything you need for your application out of the box (in our case, routing). Therefore, we will need to install react router.

React router has different components for web applications and for native ones. Since we are building a web application, we will be using react-router-dom.

To make use of routing in our application, let’s create a navigation element which will be visible at the top of the application. We will be adding this inside our App.js file and replacing the current HTML markup that is there.

Usually, in a non React project, we would put a relative path to our HTML pages for each section. That way, the browser knows where to load the data from.

But in our project, we won’t have different HTML pages for each section. We will just load a different component. The markup that used to be inside of App.js will now be found inside of a component called Home.

As we have created three sections in our navgiation and taken care of the home section, let’s give another example with the About section.

We’ll create a new file called About.jsx that will hold our template and code for the about section.

You may be asking yourself, how will the application know to redirect the user once they click on the about link? For that we will use a component called Route.

The Route is one of the most important components in react-router because it lets you render different component based on the path of the URL. For our project, we will use the code below inside of App.js just below the navigation markup.

You can see that we created two routes for home and about. The Switch component lets us group route components together and it will only match one of them.

Our combined App.js file looks like this:

One last thing we should do is wrap our entire project in a Router component. We need to do this because it enables us to use routing in our application. We will be using the BrowserRouter component as it uses HTML5’s history API.

If we run things locally, everything seems to work. Let’s deploy our augmented project to GitHub Pages and see what the result is.

How to Handle Routing Using HashRouter

At first glance, everything seems to be working fine. But when you try refreshing the page or navigating through the browser itself, you’ll keep getting 404 errors.

Why does this happen? Because GitHub Pages does not support browser history like your browser does. In our case, the route https://tomerpacific.github.io/starter-project/about doesn’t help GitHub Pages understand where to point the user (since it is a frontend route).

To overcome this problem, we need to use a Hash Router instead of a Browser Router in our application. This type of router uses the hash portion of the URL to keep the UI in sync with the URL.

You can read more about this here.

Deploy your application again and you’ll be satisfied with the result. No more 404 errors.

This article was inspired by working on a project of mine. You can view it below:

Источник

React приложение на github pages

Deploying a React App* to GitHub Pages

* created using create-react-app

In this tutorial, I’ll show you how I deployed a React app—which I created using create-react-app —to GitHub Pages.

This repository contains the files related to the app. The master branch contains the app’s source code (the code the app’s developers edit), and the gh-pages branch contains a built version of the app (i.e. the code that GitHub Pages serves to the app’s visitors).

The remainder of this document contains a tutorial on creating a React app (using create-react-app ) and deploying that app to GitHub Pages.

An adequate version of Node.js is installed. Here’s the adequate version I use:

An adequate version of npm is installed. Here’s the adequate version I use:

An adequate version of create-react-app is installed. Here’s the adequate version I use:

(Optional) An adequate version of sed is installed. Here’s the adequate version I use:

Create an empty repository on GitHub. (2 minutes)

Create a new React app on your computer. (5 minutes)

Install the gh-pages package as a «dev-dependency» of the app. (1 minute)

Add some properties to the app’s package.json file. (3 minutes)

Create a git repository in the app’s folder. (1 minute)

Add the GitHub repository as a «remote» in your local git repository. (1 minute)

Generate a production build of your app, and deploy it to GitHub Pages. (2 minutes)

Optionally, commit your source code to the «master» branch and push your commit to GitHub. (1 minute)

About

Deploying a React App (created using create-react-app) to GitHub Pages

Источник

Понравилась статья? Поделить с друзьями:
Добавить комментарий
  • Как сделать успешный бизнес на ритуальных услугах
  • Выездной кейтеринг в России
  • Риски бизнеса: без чего не обойтись на пути к успеху
  • react отправка формы на сервер
  • react модальное окно с формой