Cómo habilitar la sintaxis de ES6 (y más allá) con Node y Express

¿Alguna vez ha intentado escribir aplicaciones de front-end usando la sintaxis de ES6, pero luego, cuando decidió aprender el desarrollo de back-end con Node.js y Express, se dio cuenta de que no puede usar cosas como import fromy   export default? Si es así, ¡has venido al lugar correcto! Esta es una guía paso a paso sobre cómo configurar sus entornos de desarrollo y producción, configurar scripts y, como beneficio adicional, ¡aprenderemos cómo agregar pruebas!

Tabla de contenido / Resumen de temas

  • ¿Como funciona?
  • Prerrequisitos
  • Instalación express
  • Configurar scripts
  • Prima
  • TL; DR

¿Como funciona? Una visión de alto nivel de lo que necesitamos

Para permitir una experiencia similar a la del desarrollo de aplicaciones para el usuario mientras desarrolla aplicaciones de fondo, aquí tiene una vista de alto nivel de los procesos que ocurren en su proyecto.

Transpilador de código de ES6 + a ES5

Necesitamos un paquete que traduzca ES6 y la sintaxis superior al código ES5. El código ES5 es el estilo de sintaxis JS que se puede leer en node.js, como module.exportso var module = require('module'). Tenga en cuenta que en la actualidad, casi el 99% de la sintaxis de ES6 + se puede utilizar en Node.js. Aquí es donde brilla el paquete llamado babel .

Babel toma un archivo js, ​​convierte el código que contiene y genera un archivo nuevo.

Script que elimina archivos

Siempre que cambiamos algo en nuestro código, lo enviamos al transpilador y genera una copia nueva cada vez. Es por eso que necesitamos una secuencia de comandos que elimine los archivos antes de que ingrese la nueva copia transpilada. Y para eso, existe un paquete llamado rimraf. Rimraf elimina archivos. Lo demostraremos más tarde.

Vigilante de cambios de archivos

Cuando se codifica en Node.js, el reinicio automático de nuestro servidor no sale de la caja como cuando se hace un proyecto creado sobre create-react-app o vue-cli. Es por eso que instalaremos un paquete llamado nodemon, que ejecuta algo cada vez que cambiamos un archivo en nuestro código. Podemos aprovechar nodemon para reiniciar nuestro servidor cada vez que se cambia un archivo.

Así que esa es la vista de alto nivel de cómo funciona bajo el capó. Con eso, comencemos con cómo debemos configurar o proyectar.

Prerrequisitos

Antes de comenzar, primero necesitamos configurar algunas cosas.

  1. Asegúrese de tener Node.js y npm instalados. Recomiendo instalar su última versión LTS o estable actual. Puede instalarlo a través de Node.js Source o NVM (Node Version Manager)
  2. Conocimientos básicos de los comandos de terminal. La mayoría de los comandos están en el tutorial de todos modos, por lo que no tiene que preocuparse por ellos.
  3. Asegúrese de tener su terminal abierta y su editor de texto favorito instalado.

Eso es todo, ¡estamos listos para comenzar!

Instalación de Express

Usando el generador Express, crearemos un nuevo proyecto con código generado, moveremos algunos archivos y convertiremos código a la sintaxis ES6. Necesitamos convertirlo en esta etapa temprana porque necesitamos una forma de verificar si nuestro código ES6 funciona.

Configuración del proyecto

Ejecute este comando en su terminal. Puedes nombrar your-project-namecon el nombre que te guste. --no-viewflag significa que no usaremos ningún motor de plantillas como manubrios, ejs o pug, para nuestra aplicación skeleton Express.

npx express-generator your-project-name --no-view

Después de crear su aplicación, debe ir al directorio de su aplicación. Para terminales Windows Powershell y Linux, use:

cd your-project-name

A continuación, abra el editor de texto que desee. Para mí, solo uso VSCode, así que tengo mi terminal y el editor de texto abiertos al mismo tiempo. Pero puede usar cualquier editor de texto que desee.

Instalar paquetes y mover y eliminar archivos

Una vez que tenemos el proyecto generado listo, necesitamos installlas dependencias y mover algunas carpetas. Ejecute este comando para instalar Express y otros paquetes.

npm install

Mientras espera a que se instalen las dependencias, siga estos pasos.

  • crear una server/carpeta
  • Pon bin/, app.jsy routes/dentro de la server/carpeta.
  • Cambiar nombre www, que se encuentra en binawww.js
  • Deje la public/carpeta en la raíz de su proyecto.

Su estructura de archivo se verá así:

Ahora, debido a que modificamos la estructura del archivo, nuestro script de inicio del servidor no funcionará. Pero lo arreglaremos en el camino.

Conversión a código ES6

Convertir el código generado a ES6 es un poco tedioso, así que publicaré el código aquí y siéntete libre de copiarlo y pegarlo.

Código para bin/www.js:

Ahora, debido a que modificamos la estructura del archivo, nuestro script de inicio del servidor no funcionará. Esto es lo que haremos para solucionarlo. En su archivo package.json, cambie el nombre del script de inicio para que se serverencuentre en un objeto JSON llamado"scripts"

// package.json { "name": "your-project-name", // ....other details "scripts": { "server": "node ./server/bin/www" } }

Verá que cambiamos la ruta del archivo de ./bin/wwwa ./server/bin/wwwporque movimos archivos a server/. Usaremos el script de inicio más adelante.

¡Intentalo! Intente ejecutar el servidor escribiendo npm run serveren su terminal y vaya a localhost:3000en su navegador.

Conversión del código de nivel superior para utilizar importaciones de ES6

Convertir el código generado a ES6 es un poco tedioso, así que publicaré el código aquí y siéntete libre de copiarlo y pegarlo.

Código para bin/www.js:

// bin/www.js /** * Module dependencies. */ import app from '../app'; import debugLib from 'debug'; import http from 'http'; const debug = debugLib('your-project-name:server'); // ..generated code below.

Almost all of our modifications are only at the top and bottom of the files. We are leaving other generated code as is.

Code for routes/index.js and routes/users.js:

// routes/index.js and users.js import express from 'express'; var router = express.Router(); // ..stuff below export default router;

Code for app.js:

// app.js import express from 'express'; import path from 'path'; import cookieParser from 'cookie-parser'; import logger from 'morgan'; import indexRouter from './routes/index'; import usersRouter from './routes/users'; var app = express(); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, '../public'))); app.use('/', indexRouter); app.use('/users', usersRouter); export default app;

In app.js , because we left public/ at the project root , we need to change the Express static path one folder up. Notice that the path 'public' became '../public' .

app.use(express.static(path.join(__dirname, '../public')));

Okay we’re done with converting the code! Let’s setup our scripts now.

Setting up Scripts

In setting up scripts, each script performs a different role. And we reuse each npm script. And for our development and production environments, they have a different configuration. (Almost identical, you’ll see later) That’s why we need to compose our scripts so we can use them without repeatedly typing the same stuff all over again.

Install `npm-run-all`

Since some terminal commands won’t work on windows cmd, we need to install a package called npm-run-all so this script will work for any environment. Run this command in your terminal project root.

npm install --save npm-run-all

Install babel, nodemon, and rimraf

Babel is modern JavaScript transpiler. A transpiler means your modern JavaScript code will be transformed to an older format that Node.js can understand. Run this command in your terminal project root. We will be using the latest version of babel (Babel 7+).

Note that Nodemon is our file watcher and Rimraf is our file remover packages.

npm install --save @babel/core @babel/cli @babel/preset-env nodemon rimraf

Adding transpile script

Before babel starts converting code, we need to tell it which parts of the code to translate. Note that there are a lots of configuration available, because babel can convert a lot of JS Syntaxes for every different kinds of purpose. Luckily we don’t need to think about that because there’s an available default for that. We are using default config called as preset-env (the one we installed earlier) in our package.json file to tell Babel in which format we are transpiling the code.

Inside your package.json file, create a "babel" object and put this setting.

// package.json { // .. contents above "babel": { "presets": ["@babel/preset-env"] }, }

After this setup we are now ready to test if babel really converts code. Add a script named transpile in your package.json:

// package.json "scripts": { "start": "node ./server/bin/www", "transpile": "babel ./server --out-dir dist-server", }

Now what happened here? First we need to run the cli command babel , specify the files to convert, in this case, the files in server/ and put the transpiled contents in a different folder called dist-server in our project root.

You can test it by running this command

npm run transpile

You’ll see a new folder pop up.

Yay it worked! ✅ As you can see, there’s a folder that has the same folder structure as our server folder but with converted code inside. Pretty cool right? Next step is to run try if our server is running!

Clean script

To have a fresh copy every-time we transpile code into new files, we need a script that removes old files. Add this script to your package.json

"scripts": { "server": "node ./dist-server/bin/www", "transpile": "babel ./server --out-dir dist-server", "clean": "rimraf dist-server" }

This npm script that we made means it removes the folder dist-server/

Now to combine transpile and clean, add a script called build , which combines the two processes.

// scripts "build": "npm-run-all clean transpile"

Running dev script

Now we have a build script, we need to run our dev server. We’ll add a script called dev in our package.json. This takes care of setting our Node Environment to “development”, removing old transpiled code, and replacing it with a new one.

"scripts": { "build": "npm-run-all clean transpile" "server": "node ./dist-server/bin/www", "dev": "NODE_ENV=development npm-run-all build server", "transpile": "babel ./server --out-dir dist-server", "clean": "rimraf dist-server" }

Note here that we’ve changed again the file we are running on our server script. We’re running the file-path with the transpiled code, found in dist-server/.

Adding prod scripts

If we have a dev script that sets the Node Environment to development, we have a prod script that sets it to “production.” We use this configuration when we are deploying. (Heroku, AWS, DigitalOcean, etc..) We’re now adding again our start script and prod script in our package.json again.

"scripts": { "start": "npm run prod" "build": "npm-run-all clean transpile" "server": "node ./dist-server/bin/www", "dev": "NODE_ENV=development npm-run-all build server", "prod": "NODE_ENV=production npm-run-all build server", "transpile": "babel ./server --out-dir dist-server", "clean": "rimraf dist-server" }

We set start script default to prod because start script is being used always by deployment platforms like AWS or Heroku to start a server.

Try either by running npm start or npm run prod .

// package.json ... "nodemonConfig": { "exec": "npm run dev", "watch": ["server/*", "public/*"], "ignore": ["**/__tests__/**", "*.test.js", "*.spec.js"] }, "scripts": { // ... other scripts "watch:dev": "nodemon" }

How about auto-restarting the server whenever a file change?

One final script, in order to complete our development setup. We need to add a file watcher script that runs a command whenever a change is made in a file. Add a JSON Object named “nodemonConfig” in your package.json. This is where we store what we tell the watcher what to do when a file changes.

Also, add a script called watch:dev in your package.json

// package.json ... "nodemonConfig": { "exec": "npm run dev", "watch": ["server/*", "public/*"], "ignore": ["**/__tests__/**", "*.test.js", "*.spec.js"] }, "scripts": { // ... other scripts "watch:dev": "nodemon" }

Nodemon config contains settings related to

  • Which command to run whenever a file changes, in our case npm run dev
  • What folders and files to watch
  • And which files to ignore

More about configuration of nodemon here.

Now that we have our file watcher, you can now just run npm run watch:dev , code, and save your file. and whenever you go to localhost:3000 , you’ll see the changes. Try it out!

Bonus: Add tests!

To add tests in our project, simply install Jest from npm, add a few config, and add a script called test in our package.json

npm i -D jest

Add an object called “jest”, and a test script in your package.json

// package.json ... "jest": { "testEnvironment": "node" }, "scripts": { // ..other scripts "test": "jest" }

Try it out, make a file sample.test.js, write any tests, and run the script!

npm run test

TL;DR

Here are the simplified steps for how to enable ES6 in Node.js. I’ll also include the repo so you can copy and inspect the whole code.

  • Make a new project using express your-project-name terminal command.
  • Move the bin/, routes/ and app into a new folder called src/ , and convert the code into ES6. Also don’t forget to rename bin/www to www.js
  • Install all the dependencies and devDependencies
npm i npm-run-all @babel/cli @babel/core @babel/preset-env nodemon rimraf --save npm i -D jest
  • Add these scripts to your package.json
"scripts": { "start": "npm run prod", "build": "npm-run-all clean transpile", "server": "node ./dist-server/bin/www", "dev": "NODE_ENV=development npm-run-all build server", "prod": "NODE_ENV=production npm-run-all build server", "transpile": "babel ./server --out-dir dist-server", "clean": "rimraf dist-server", "watch:dev": "nodemon", "test": "jest" }
  • Put configurations for babel, nodemon, and jest in your package.json
"nodemonConfig": { "exec": "npm run dev", "watch": [ "server/*", "public/*" ], "ignore": [ "**/__tests__/**", "*.test.js", "*.spec.js" ] }, "babel": { "presets": [ "@babel/preset-env" ] }, "jest": { "testEnvironment": "node" },
  • Test your scripts by running npm run your-script-here
  • You’ll see the complete repo at my github

Notes and disclaimers

Note that this setup may not be proved ideal for all situations, specially for big projects. (like 1k files of code). Transpiling step and deleting might slow down your development environment. Plus, ES Modules, is almost coming to node. But, nevertheless, this is a good eductational material to understand how transipiling runs under the hood like when we are developing front-end apps :)

Conclusion

All right! I hope you learned a lot. Thank you for reading this far.

Happy Coding!

Check the full repo here.

This article is published in freeCodecamp news.

? Twitter - ? freeCodeCamp -  ? Portfolio - ⚛️ Github