как задеплоить react приложение на netlify
Как развернуть React-приложение в Netlify
Apr 1, 2019 · 5 min read
Я научу вас развертке и хостингу React приложения с Netlify.
Netlify — это сервис для автоматизации сборки, развертывания и управления сайтами. В настоящее время Netlify считается одним из самых простых и быстрых решений по развертыванию приложений.
В Netlify есть бесплатный тариф. Для начала, авторизуемся на Netlify любым из доступных способов (Github, Gitlab, Bitbucket, адрес почты) на странице входа.
Начнем создание сборки нашего приложения со следующей команды:
Так мы создали папку сборки. В ней будут содержаться все файлы для развертывания в рабочей среде.
Есть два способа развертывания нашего приложения в Netlify.
Перетаскивание
В Netifly в се до безобразия просто — перетащите папку сборки в онлайн-приложение (крайнее правое изображение выше). Так ваше приложение будет развернуто с реальным URL.
Примечание: Онлайн-приложение Netlify — это экран, который появляется после авторизации в Netlify.
Netlify CLI
Также в Netifly доступен интерфейс командной строки, который позволяет развертывать приложение прямо из командной строки. Именно этим мы сейчас и займемся.
Для начала, установим CLI с помощью следующей команды:
Теперь мы готовы к развертыванию. Для развертки приложения необходимо удостовериться, что мы находимся в папке проекта. Затем выполняем следующую команду:
Возможно, мы увидим всплывающее окно с предложением авторизоваться на Netlify и получить доступ к Netlify CLI.
Нажмем Authorize. После того, как мы авторизовались на сайте, следуйте указаниям командной строки для правильной развертки приложения.
Подсказки командной строки
1. В консоли вы видите: “ This folder isn’t linked to a site yet. What would you like to do?” (Эта папка еще не привязана к сайту. Что Вы хотите сделать?) Здесь CLI спрашивает, хотите ли вы привязать эту директорию к существующему сайту или же создать и настроить новый сайт. Поскольку мы делаем новый сайт, то выбираем Create & configure a new site (Создать и настроить новый сайт).
2. Здесь нам предлагают выбрать название сайта. Я указываю portfolio on netlify (Вы можете придумать любое название).
3. Теперь система спрашивает, какой аккаунт Netlify вы собираетесь использовать. Я выбираю my account (Abhishek Jakhar), вы можете выбрать свой.
4. В качестве пути развертывания необходимо указать директорию сборки проекта, в которой содержатся ресурсы для развертки. Печатаем build и нажимаем Enter.
5. Мы создали сайт. Сначала он будет развертываться на черновом URL. Вы можете увидеть его, если скопируете и вставите URL в браузер.
Возвращаемся обратно в консоль и видим надпись: “If everything looks good on your draft URL, take it to live with the — prod flag” (Если в черновом URL все выглядит хорошо, перейдите в рабочую версию через флажок — prod).
Для перехода в рабочую среду выполним команду из подсказки в командной строке:
Нас опять просят указать путь развертывания, то есть папку сборки, но уже к реальной версии.
В результате в консоли мы получаем два URL. Unique Deploy URL (Уникальный URL развертывания), который представляет собой уникальный URL для каждой индивидуальной развертки, и Live URL (реальный URL), в котором всегда отображается самое последнее развертывание.
Поэтому каждый раз при обновлении сайта и его развертывании, вы будете получать уникальный адрес этой версии. То есть, если вы делаете многократную развертку, то получите много уникальных URL, которые позволят вам направлять пользователей к отдельным версиям приложения. Но Live URL всегда отображает только самые последние изменения для этого URL.
Примечание: Netlify автоматически и бесплатно защищает ваш сайт через HTTPS.
Ошибка Page Not Found
Если вы публикуете приложение, которое использует маршрут React Router, то нужно будет настроить редирект и добавить правила замены для URL. В противном случае, при нажатии на любой элемент навигации, будет выскакивать ошибка 404.
Настроить переадресацию и правила замены в Netlify очень просто. Нам нужно добавить файл в папку сборки приложения и назвать его _redirects. Внутри этого файла прописываем правило замены.
Благодаря этому правилу при любом запрашиваемом URL браузер будет открывать файл index.html, а не выдавать ошибку 404.
How to deploy a React application to Netlify
by Abhishek Jakhar
How to deploy a React application to Netlify
I’m going to teach you how to deploy and host your React app with Netlify.
Netlify is a service that automates builds, deployments and manages your websites. It’s one of the fastest and easiest deployment solutions these days.
Netlify offers a free plan. So first, we will log in to Netlify using any one of the options(Github, Gitlab, Bitbucket, Email) given on the login page.
Left(Login Page) Center(Authorization) Right(Netlify Online App)
We will start by creating a build of our application by running this command:
So, now our build folder will get generated which will contain all the production-ready files.
Now, there are two ways to deploy our application to Netlify.
Drag & Drop
Netifly has made it so easy that we have to just drag and drop our build folder into their online app (Rightmost image above), and our application will get deployed to a live URL.
Note: Netlify online app is the screen which appears after you have logged into your netlify account.
Netlify CLI
Netifly also provides a command line interface that lets you deploy your app straight from the command line. That’s what we will do now.
So first, we’ll install the CLI using the following command:
Now, we’re ready to deploy it. To deploy the application we have to make sure that we’re in the project folder and then we will run this command:
We might get a pop-up window which will ask us to log in with Netlify and grant access to the Netlify CLI.
Pop-Up window asking you to log in with Netlify and grant access to the Netlify CLI
Now, we’ll click Authorize. Now that we’re authorized, we can follow the command line prompts to deploy the app.
Command Line Prompts
2. It gives us the option to give our site a name. I’ll type portfolio on netlify (You can type any available name which you like).
3. Now it will ask for the Netlify account which you want to use, so I will select my account (Abhishek Jakhar), you can select yours.
4. Now, as deploy path, we need to specify our project’s build directory which contains the assets for deployment. So, we will type build there and press enter.
5. Now, our site will get created and will be deployed to a draft URL first, which we can view by copying and pasting the URL in the browser.
So to make our app live, we’ll run the command shown on the command line
It will ask us one more time to specify the deploy path for the live build which again is our build folder.
Now, in the console output, we get two URLs. A Unique Deploy URL, which represents the unique URL for each individual deployment, and a Live URL which always displays your latest deployment.
So each time you update your website and deploy it, you’re going to get a unique URL for that deployment. Basically, if we deploy multiple times we will be having multiple unique URLs so that you can point users to a specific version of your application. But the live URL always displays your latest changes at the same URL.
Note: Netlify automatically secures your site over HTTPS for free.
Page Not Found Error
If you’re publishing an app that uses a router like React Router you’ll need to configure redirects and rewrite rules for your URLs. Because when we click on any navigation item to change the page (route) and refresh the browser, we get a 404 error page.
So Netlify makes configuring redirects and rewrite rules for your URLs really easy. We’ll need to add a file inside the build folder of our app named _redirects. Inside the file, we need to include the following rewrite rule.
This rewrite rule is going to serve index.html file instead of giving a 404, no matter what URL the browser requests.
The _redirects file inside the build folder containing redirect rule
That’s all there is to it. On netlify.com you can see your site settings. There you can do stuff like set up a custom domain or connect the site to a GitHub repository.
I hope you’ve found this post informative and helpful. I would love to hear your feedback!
Thank you for reading!
If this article was helpful, tweet it.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)
Donations to freeCodeCamp go toward our education initiatives and help pay for servers, services, and staff.
Как развернуть React-приложение в Netlify
Я научу вас развертке и хостингу React приложения с Netlify.
Netlify — это сервис для автоматизации сборки, развертывания и управления сайтами. В настоящее время Netlify считается одним из самых простых и быстрых решений по развертыванию приложений.
В Netlify есть бесплатный тариф. Для начала, авторизуемся на Netlify любым из доступных способов (Github, Gitlab, Bitbucket, адрес почты) на странице входа.
Начнем создание сборки нашего приложения со следующей команды:
Так мы создали папку сборки. В ней будут содержаться все файлы для развертывания в рабочей среде.
Есть два способа развертывания нашего приложения в Netlify.
Перетаскивание
В Netifly все до безобразия просто — перетащите папку сборки в онлайн-приложение (крайнее правое изображение выше). Так ваше приложение будет развернуто с реальным URL.
Примечание: Онлайн-приложение Netlify — это экран, который появляется после авторизации в Netlify.
Netlify CLI
Также в Netifly доступен интерфейс командной строки, который позволяет развертывать приложение прямо из командной строки. Именно этим мы сейчас и займемся.
Для начала, установим CLI с помощью следующей команды:
Теперь мы готовы к развертыванию. Для развертки приложения необходимо удостовериться, что мы находимся в папке проекта. Затем выполняем следующую команду:
Возможно, мы увидим всплывающее окно с предложением авторизоваться на Netlify и получить доступ к Netlify CLI.
Нажмем Authorize. После того, как мы авторизовались на сайте, следуйте указаниям командной строки для правильной развертки приложения.
Подсказки командной строки
1. В консоли вы видите: “This folder isn’t linked to a site yet. What would you like to do?” (Эта папка еще не привязана к сайту. Что Вы хотите сделать?) Здесь CLI спрашивает, хотите ли вы привязать эту директорию к существующему сайту или же создать и настроить новый сайт. Поскольку мы делаем новый сайт, то выбираем Create & configure a new site (Создать и настроить новый сайт).
2. Здесь нам предлагают выбрать название сайта. Я указываю portfolio on netlify (Вы можете придумать любое название).
3. Теперь система спрашивает, какой аккаунт Netlify вы собираетесь использовать. Я выбираю my account (Abhishek Jakhar), вы можете выбрать свой.
4. В качестве пути развертывания необходимо указать директорию сборки проекта, в которой содержатся ресурсы для развертки. Печатаем build и нажимаем Enter.
5. Мы создали сайт. Сначала он будет развертываться на черновом URL. Вы можете увидеть его, если скопируете и вставите URL в браузер.
Возвращаемся обратно в консоль и видим надпись: “If everything looks good on your draft URL, take it to live with the — prod flag” (Если в черновом URL все выглядит хорошо, перейдите в рабочую версию через флажок — prod).
Для перехода в рабочую среду выполним команду из подсказки в командной строке:
Нас опять просят указать путь развертывания, то есть папку сборки, но уже к реальной версии.
В результате в консоли мы получаем два URL. Unique Deploy URL (Уникальный URL развертывания), который представляет собой уникальный URL для каждой индивидуальной развертки, и Live URL (реальный URL), в котором всегда отображается самое последнее развертывание.
Поэтому каждый раз при обновлении сайта и его развертывании, вы будете получать уникальный адрес этой версии. То есть, если вы делаете многократную развертку, то получите много уникальных URL, которые позволят вам направлять пользователей к отдельным версиям приложения. Но Live URL всегда отображает только самые последние изменения для этого URL.
Примечание: Netlify автоматически и бесплатно защищает ваш сайт через HTTPS.
Ошибка Page Not Found
Если вы публикуете приложение, которое использует маршрут React Router, то нужно будет настроить редирект и добавить правила замены для URL. В противном случае, при нажатии на любой элемент навигации, будет выскакивать ошибка 404.
Настроить переадресацию и правила замены в Netlify очень просто. Нам нужно добавить файл в папку сборки приложения и назвать его _redirects. Внутри этого файла прописываем правило замены.
Благодаря этому правилу при любом запрашиваемом URL браузер будет открывать файл index.html, а не выдавать ошибку 404.
3 ways to deploy React apps to Netlify
December 29, 2020 6 min read 1690
Over the past few years, Netlify has easily worked its way into the hearts and minds of many developers. Some developers consider Netlify to be the best thing that’s ever happened to them when it comes to software development and deployment.
Netlify prides itself on being the fastest way to build amazing sites. It can be a serious boon to your productivity. Netlify has a popular tagline that can serve as an anchor for this tutorial:
“Just git push to deploy worldwide.”
Prerequisites
The goal here is to take an in-depth look at deploying React apps using Netlify. To follow along with this tutorial, you’ll need a working knowledge of the following:
What does Netlify have to offer?
Aside from the fact that most of its features are absolutely free, Netlify also eases deployments by providing the following:
Preparing the React application for deployment
There are three major ways for deploying applications to Netlify that we’ll be highlighting today.
Before we dive into the specifics of each method, let’s touch on some generic steps that apply across all the different deployment methods.
Creating a React app
In the terminal, we’ll run the following command:
The above command installs all the packages required to create a simple React application alongside some static files, thereby giving us a base to work with.
For this tutorial, we’ll be deploying this sample app as is. Please feel free to make as many changes as you want to your sample application.
Create a build directory
Next, we’ll want to create a build of our application in a production-ready build folder.
To accomplish this, let’s run the command below:
This command generates a build folder that represents a minified version of the entire application, containing everything we would need to deploy the application.
Now that we have our React app ready to be deployed, we can push this app to our version control of choice. In this case, we’ll choose Github.
Version control with Github
There are so many version control systems out there, but for the sake of this tutorial, we’ll focus on the Github version control system. Follow the guide here to get started with Github.
We’ll create a Github repository with any name we want. Then, we’ll push our React app to the Github repo as shown in the image below. You can find my sample repo here.
Once we are done with this, we can dive deep into the different methods for deploying our app to Netlify.
3 methods for deploying React applications to Netlify
Method 1: Netlify UI
This method is best suited for developers who would rather deploy and configure applications manually using the Netlify user interface rather than using the command line terminal.
Connect Netlify account with Github account
If you do not have a Netlify account already, you can create a free one here.
We’re going to log into Netlify with our already created Github account and follow the prompts to authorize Netlify Auth:
After authorizing Netlify Auth, we are redirected to our Github teams page. Next, we’ll need to create a New Site from Git, as shown below:
Authorize Netlify to access repositories
Still on the create a new site page, we would be prompted to authorize Netlify to access the Github repositories. We can choose to give Netlify access to the entire Github account, or we can give Netlify access to a specific repository by clicking on the “Configure Netlify on GitHub” button at the bottom of the page.
Build options & deploy
After selecting the repository where the React application is hosted and choosing the deployment branch from the step above, we specify the basic build settings required to deploy the site.
Although this page comes pre-populated with the build step, please check that it conforms with the command that builds your application.
Upon successful deployment, we can preview our site with the test domain it returns.
Configuring site domain
Once we have previewed our React app deployment and feel good about how it looks, we can now configure a proper domain to serve our application. In the Deploys tab, we see details of site deployment. That’s where we register the subdomain we would like to use for our React application.
If we want to use a preregistered domain, Netlify will want us to verify that the domain is ours. We’ll click on set up a custom domain from the image above. This prompts us to verify our custom domain before Netlify can configure it.
Once this is successfully verified, we can access our application on the configured domain.
Netlify drag and drop
This method is pretty similar to the first method described above. However, the drag and drop feature is unique in that it utilizes the online app feature. It is specifically suited for super fast deployments.
Log in to your Netlify account
We can follow the first step of the first method above to connect our Github account to our Netlify account. However, we’ll see that in this instance we are greeted with a blank page as shown below. This is what we refer to as the online app feature.
We will not be creating a new site from git like we did in the first method.
Drag and drop
Since we have our React app with an up-to-date build folder, all we have to do is drag the build folder into the blank space above. This black space is otherwise known as the online app. Netlify does the deployment magic for us.
Configuring site domain
This follows the same approach as configuring the site domain in the first method described above.
Netlify CLI
This method is for developers who are more comfortable running deployments from the command line terminal as opposed to using the UI or the drag and drop feature
Install Netlify CLI
Installing the Netlify CLI is very quick and easy. It’s as easy as running an npm install command as shown below:
Authorize CLI
After installing the CLI, we navigate into our working directory and run the following commands to authorize our Netlify CLI against the Netlify account:
Note: Ensure that pop-up is not blocked in the browser window for redirects.
Running the Netlify deploy command will redirect us to a browser window requesting authorization for the Netlify CLI:
Deploy application
Now that the CLI has adequate permissions to access the Netlify account, we can go ahead and deploy the application.
There are a few command line prompts that we’ll want to go through together. We can navigate the prompts by using the arrow keys on your device.
CLI prompt 1: This folder isn’t linked to a site yet. What would you like to do?
This is the first prompt after authorizing the app. It wants to know if we want to deploy this application to a pre-existing site, or to a new site. In this case, we are deploying to a new site, so we select “Create & configure a new site”.
CLI prompt 2: Choose a site name (optional)
We could decide to configure the site details from here, or leave it blank so that Netlify gives us a random name. Regardless of the option you go with here, you can always update it later.
From the image above, we can see how Netlify beautifully generates a custom domain URL from the site name.
However, even though we have a url, we are not done with the deployment just yet.
CLI prompt 3: Deploy path
Since we are running the netlify deploy command in our React app working directory, our deployment path is our build folder. As a result, we’ll just need to specify the path to our build directory in response to the prompt.
This is necessary, as only the build folder contains the production-ready files needed to deploy the application.
Now we have a URL we can test with.
Note: If the URL redirects to a webpage that throws a Page Not found error, this is an issue that has to do with an incorrect build file. Please run the netlify deploy command again and update the build file accordingly.
Deploy application to production
After testing with the website draft URL, we take our application live by running the command from our output above:
Once again, we would be required to specify the deploy path, which is the path to our build directory. After successful deployment, we get an updated website URL.
Two important things to note are the Unique deploy URL and the live URL, as shown above.
The Unique deploy URL represents the URL specific to each deployment.
The Live URL is the production website URL.
We can now access our React application from the Live URL.
Conclusion
Deploying React apps and other applications with Netlify is a seamless process, owing largely to the platform’s easy to use features.
Once the preferred deployment method is chosen and the requirements are met (e.g installing the CLI, if CLI is our preferred method), you can typically deploy your app to Netlify in under 60 seconds, all things being equal.
I hope you enjoyed creating and deploying a React application with me. Do let me know in the comment section.
Full visibility into production React apps
LogRocket is like a DVR for web apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app’s performance, reporting with metrics like client CPU load, client memory usage, and more.
The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.
Modernize how you debug your React apps — start monitoring for free.