Якщо ви новачок у світі веб-розробки, ви витратите багато часу на те, щоб навчитися будувати статичні сайти за допомогою HTML, CSS та JavaScript.
Потім ви можете почати вивчати використання популярних фреймворків, таких як React, VueJS або Angular.
Але спробувавши кілька нових ідей та запустивши деякі сайти локально, ви можете задатися питанням, як насправді розгорнути свій сайт або додаток. І, як виявляється, часом буває важко знати, з чого почати.
Особисто я вважаю, що запуск Express-сервера, розміщений на Heroku, є одним з найпростіших способів розпочати роботу. Ця стаття покаже вам, як це зробити.
Heroku - це хмарна платформа, яка підтримує ряд різних мов програмування та фреймворків.
Це не спонсорований допис - звичайно, існує безліч інших рішень, таких як:
- Цифровий океан
- Amazon Web Services
- Лазурний
- Google Cloud Platform
- Netlify
- ZEIT зараз
Перевірте їх усі та перевірте, що найбільше відповідає вашим потребам.
Особисто я знайшов Heroku найшвидшим та найпростішим у використанні "нестандартно". Безкоштовний рівень дещо обмежений з точки зору ресурсів. Однак я можу впевнено рекомендувати його для тестування.
У цьому прикладі буде розміщено простий веб-сайт із використанням сервера Express. Ось кроки високого рівня:
- Налаштування за допомогою Heroku, Git, npm
- Створіть сервер Express.js
- Створюйте статичні файли
- Розгортання до Heroku
Загалом це може зайняти близько 25 хвилин (або довше, якщо ви хочете витратити більше часу на статичні файли).
Ця стаття передбачає, що ви вже знаєте:
- Деякі основи HTML, CSS та JavaScript
- Основне використання командного рядка
- Git для початківців для контролю версій
Ви можете знайти весь код у цьому сховищі.
Налаштовуючи
Першим кроком у будь-якому проекті є налаштування всіх інструментів, які, як ви знаєте, вам знадобляться.
Вам потрібно мати:
- Вузол та npm, встановлені на вашому локальному комп'ютері (читайте, як це зробити тут)
- Git встановлений (прочитайте цей посібник)
- Встановлений CLI Heroku (ось як це зробити)
1. Створіть новий каталог та ініціалізуйте сховище Git
З командного рядка створіть новий каталог проекту та перейдіть у нього.
$ mkdir lorem-ipsum-demo $ cd lorem-ipsum-demo
Тепер ви знаходитесь у папці проекту, ініціалізуйте нове сховище Git.
⚠️Цей крок важливий, оскільки Heroku покладається на Git для розгортання коду з вашої локальної машини на хмарних серверах ⚠️
$ git init
На завершальному етапі ви можете створити файл README.md для редагування пізніше.
$ echo "Edit me later" > README.md
2. Увійдіть до Інтернету клієнтів Heroku та створіть новий проект
Ви можете увійти до Heroku, використовуючи Heroku CLI (інтерфейс командного рядка). Для цього вам потрібно мати безкоштовний акаунт Heroku.
Тут є два варіанти. За замовчуванням Heroku дозволяє вам входити через веб-браузер. Додавання -i
прапора дозволяє входити через командний рядок.
$ heroku login -i
Тепер ви можете створити новий проект Heroku. Я подзвонив своїм lorem-ipsum-demo
.
$ heroku create lorem-ipsum-demo
Присвоєння імені проекту:
- Heroku генерує випадкове ім'я для вашого проекту, якщо ви не вказали його в команді.
- Ім'я буде частиною URL-адреси, за якою ви можете отримати доступ до свого проекту, тому виберіть ту, яка вам подобається.
- Це також означає, що вам потрібно вибрати унікальну назву проекту, яку ніхто інший не використовував.
- Пізніше можна перейменувати свій проект (тому не турбуйтеся надто про те, щоб отримати ідеальне ім’я прямо зараз).
3. Ініціюйте новий проект npm та встановіть Express.js
Далі ви можете ініціалізувати новий проект npm, створивши файл package.json. Для цього скористайтеся наведеною нижче командою.
Цей крок є вирішальним. Heroku покладається на те, що ви надаєте файл package.json, щоб знати, що це проект Node.js, коли він створює ваш додаток ⚠️
$ npm init -y
Далі встановіть Express. Express є широко використовуваною серверною структурою для NodeJS.
$ npm install express --save
Нарешті, ви готові розпочати кодування!
Написання простого експрес-сервера
Наступним кроком є створення файлу під назвою app.js
, який запускає експрес-сервер локально.
$ touch app.js
Цей файл буде точкою входу для програми, коли вона буде готова. Це означає, що для запуску програми потрібна одна команда:
$ node app.js
Але спочатку потрібно написати якийсь код у файлі.
4. Редагуйте вміст app.js
Відкрийте app.js
у своєму улюбленому редакторі. Напишіть код, показаний нижче, і натисніть "Зберегти".
// create an express app const express = require("express") const app = express() // use the express-static middleware app.use(express.static("public")) // define the first route app.get("/", function (req, res) { res.send("Hello World!
") }) // start the server listening for requests app.listen(process.env.PORT || 3000, () => console.log("Server is running..."));
Коментарі повинні допомогти вказати, що відбувається. Але давайте швидко розіб’ємо код, щоб зрозуміти його далі:
- The first two lines simply require the Express module and create an instance of an Express app.
- The next line requires the use of the
express.static
middleware. This lets you serve static files (such as HTML, CSS and JavaScript) from the directory you specify. In this case, the files will be served from a folder calledpublic
. - The next line uses
app.get()
to define a URL route. Any URL requests to the root URL will be responded to with a simple HTML message. - The final part starts the server. It either looks to see which port Heroku will use, or defaults to 3000 if you are running locally.
⚠️The use of process.env.PORT || 3000
in the last line is important for deploying your app successfully ⚠️
If you save app.js
and start the server with:
$ node app.js
You can visit localhost:3000 in your browser and see for yourself the server is running.
Create your static files
The next step is to create your static files. These are the HTML, CSS and JavaScript files you will serve up whenever a user visits your project.
Remember in app.js
you told the express.static
middleware to serve static files from the public
directory.
The first step is of course to create such a directory and the files it will contain.
$ mkdir public $ cd public $ touch index.html styles.css script.js
5. Edit the HTML file
Open index.html
in your preferred text editor. This will be the basic structure of the page you will serve to your visitors.
The example below creates a simple landing page for a Lorem Ipsum generator, but you can be as creative as you like here.
Lorem Ipsum generator
How many paragraphs do you want to generate?
Generate Copy!
6. Edit the CSS file
Next up is editing the CSS file styles.css
. Make sure this is linked in your HTML file.
The CSS below is for the Lorem Ipsum example. But again, feel free to be as creative as you want.
h1 { font-family: 'Alegreya' ; } body { font-family: 'Source Sans Pro' ; width: 50%; margin-left: 25%; text-align: justify; line-height: 1.7; font-size: 18px; } input { font-size: 18px; text-align: center; } button { font-size: 18px; color: #fff; } #generate { background-color: #09f; } #copy { background-color: #0c6; }
7. Edit the JavaScript file
Finally, you might want to edit the JavaScript file script.js
. This will let you make your page more interactive.
The code below defines two basic functions for the Lorem Ipsum generator. Yes, I used JQuery - it's quick and easy to work with.
$("#generate").click(function(){ var lorem = $("#lorem"); lorem.html(""); var quantity = $("#quantity")[0].valueAsNumber; var data = ["Lorem ipsum", "quia dolor sit", "amet", "consectetur"]; for(var i = 0; i < quantity; i++){ lorem.append(""+data[i]+"
"); } }) $("#copy").click(function() { var range = document.createRange(); range.selectNode($("#lorem")[0]); window.getSelection().removeAllRanges(); window.getSelection().addRange(range); document.execCommand("copy"); window.getSelection().removeAllRanges(); } )
Note that here, the data
list is truncated to make it easier to show. In the actual app, it is a much longer list of full paragraphs. You can see the entire file in the repo, or look here for the original source.
Deploying your app
After writing your static code and checking it all works as expected, you can get ready to deploy to Heroku.
However, there are a couple more things to do.
8. Create a Procfile
Heroku will need a Procfile to know how to run your app.
A Procfile is a "process file" which tells Heroku which command to run in order to manage a given process. In this case, the command will tell Heroku how to start your server listening on the web.
Use the command below to create the file.
⚠️This is an important step, because without a Procfile, Heroku cannot put your server online. ⚠️
$ echo "web: node app.js" > Procfile
Notice that the Procfile has no file extension (e.g., ".txt", ".json").
Also, see how the command node app.js
is the same one used locally to run your server.
9. Add and commit files to Git
Remember you initiated a Git repository when setting up. Perhaps you have been adding and committing files as you have gone.
Before you deploy to Heroku, make sure to add all the relevant files and commit them.
$ git add . $ git commit -m "ready to deploy"
The final step is to push to your Heroku master branch.
$ git push heroku master
You should see the command line print out a load of information as Heroku builds and deploys your app.
The line to look for is: Verifying deploy... done.
This shows that your build was successful.
Now you can open the browser and visit your-project-name.herokuapp.com. Your app will be hosted on the web for all to visit!
Quick recap
Below are the steps to follow to deploy a simple Express app to Heroku:
- Create a new directory and initialise a Git repository
- Login to the Heroku CLI and create a new project
- Initialise a new npm project and install Express.js
- Edit the contents of app.js
- Edit the static HTML, CSS and JavaScript files
- Create a Procfile
- Add and commit to Git, then push to your Heroku master branch
Things to check if your app is not working
Sometimes, despite best intentions, tutorials on the Internet don't work exactly as you expected.
The steps below should help debug some common errors you might encounter:
- Did you initialise a Git repo in your project folder? Check if you ran
git init
earlier. Heroku relies on Git to deploy code from your local machine. - Did you create a package.json file? Check if you ran
npm init -y
earlier. Heroku requires a package.json file to recognise this is a Node.js project. - Is the server running? Make sure your Procfile uses the correct file name to start the server. Check you have
web: node app.js
and notweb: node index.js
. - Does Heroku know which port to listen on? Check you used
app.listen(process.env.PORT || 3000)
in your app.js file. - Do your static files have any errors in them? Check them by running locally and seeing if there are any bugs.
Thanks for reading - if you made it this far, you might want to checkout the finished version of the demo project.