Si es nuevo en el mundo del desarrollo web, dedicará mucho tiempo a aprender a crear sitios estáticos con HTML, CSS y JavaScript.
Luego, puede comenzar a aprender a usar marcos populares como React, VueJS o Angular.
Pero después de probar algunas ideas nuevas y ejecutar algunos sitios localmente, es posible que se pregunte cómo implementar realmente su sitio o aplicación. Y resulta que a veces puede ser difícil saber por dónde empezar.
Personalmente, creo que ejecutar un servidor Express alojado en Heroku es una de las formas más sencillas de empezar. Este artículo le mostrará cómo hacer esto.
Heroku es una plataforma en la nube que admite varios lenguajes y marcos de programación diferentes.
Esta no es una publicación patrocinada; por supuesto, hay muchas otras soluciones disponibles, como:
- Océano digital
- Servicios web de Amazon
- Azur
- Google Cloud Platform
- Netlify
- ZEIT ahora
Compruébelos todos y vea cuál se adapta mejor a sus necesidades.
Personalmente, encontré Heroku el más rápido y fácil de comenzar a usar "fuera de la caja". El nivel gratuito es algo limitado en términos de recursos. Sin embargo, puedo recomendarlo con confianza para realizar pruebas.
Este ejemplo alojará un sitio simple usando un servidor Express. Estos son los pasos de alto nivel:
- Configuración con Heroku, Git, npm
- Cree un servidor Express.js
- Crea archivos estáticos
- Implementar en Heroku
Debería tardar unos 25 minutos en total (o más si desea dedicar más tiempo a los archivos estáticos).
Este artículo asume que ya sabe:
- Algunos conceptos básicos de HTML, CSS y JavaScript
- Uso básico de la línea de comandos
- Git de nivel principiante para el control de versiones
Puedes encontrar todo el código en este repositorio.
Configurar
El primer paso en cualquier proyecto es configurar todas las herramientas que sabe que necesitará.
Necesitarás tener:
- Node y npm instalados en su máquina local (lea cómo hacer esto aquí)
- Git instalado (lea esta guía)
- La CLI de Heroku instalada (aquí se explica cómo hacerlo)
1. Cree un nuevo directorio e inicialice un repositorio de Git
Desde la línea de comando, cree un nuevo directorio de proyecto y muévase a él.
$ mkdir lorem-ipsum-demo $ cd lorem-ipsum-demo
Ahora que está en la carpeta del proyecto, inicialice un nuevo repositorio de Git.
⚠️Este paso es importante porque Heroku confía en Git para implementar código desde su máquina local a sus servidores en la nube ⚠️
$ git init
Como paso final, puede crear un archivo README.md para editarlo en una etapa posterior.
$ echo "Edit me later" > README.md
2. Inicie sesión en la CLI de Heroku y cree un nuevo proyecto
Puede iniciar sesión en Heroku mediante la CLI de Heroku (interfaz de línea de comandos). Necesitará tener una cuenta gratuita de Heroku para hacer esto.
Aquí hay dos opciones. El valor predeterminado es que Heroku le permita iniciar sesión a través del navegador web. Agregar la -i
bandera le permite iniciar sesión a través de la línea de comando.
$ heroku login -i
Ahora, puede crear un nuevo proyecto de Heroku. Llamé al mío lorem-ipsum-demo
.
$ heroku create lorem-ipsum-demo
Nombrar su proyecto:
- Heroku generará un nombre aleatorio para su proyecto si no especifica uno en el comando.
- El nombre formará parte de la URL que puede utilizar para acceder a su proyecto, así que elija una que le guste.
- Esto también significa que debe elegir un nombre de proyecto único que nadie más haya utilizado.
- Es posible cambiar el nombre de su proyecto más tarde (así que no se preocupe demasiado por obtener el nombre perfecto en este momento).
3. Inicialice un nuevo proyecto npm e instale Express.js
A continuación, puede inicializar un nuevo proyecto npm creando un archivo package.json. Utilice el siguiente comando para hacer esto.
⚠️Este paso es crucial. Heroku confía en que proporciones un archivo package.json para saber que este es un proyecto de Node.js cuando compila tu aplicación ⚠️
$ npm init -y
A continuación, instale Express. Express es un marco de servidor ampliamente utilizado para NodeJS.
$ npm install express --save
¡Finalmente, está listo para comenzar a codificar!
Escribir un servidor Express simple
El siguiente paso es crear un archivo llamado app.js
, que ejecuta un servidor Express localmente.
$ touch app.js
Este archivo será el punto de entrada para la aplicación cuando esté lista. Eso significa que el único comando necesario para iniciar la aplicación será:
$ node app.js
Pero primero, debe escribir algún código en el archivo.
4. Edite el contenido de app.js
Abre app.js
en tu editor favorito. Escriba el código que se muestra a continuación y haga clic en guardar.
// 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..."));
Los comentarios deberían ayudar a indicar lo que está sucediendo. Pero analicemos rápidamente el código para comprenderlo mejor:
- 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.