Create an account or log in

Keep learning for free! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

1 Días
22 Hrs
54 Min
53 Seg

Instalación y configuración de Express.js

3/22
Resources

How to configure an Express project with Webpack?

Developing a modern web project requires tools that enable effective configuration and optimized workflow. In this guide, we will show you how to set up an Express project with Webpack to develop efficient and well-organized applications. Learn how to handle basic tools like npm and Git while preparing your essential dependencies for an effective working environment.

How to initialize a project with npm and Git?

Initializing a project correctly is crucial to ensure that all your tools work optimally. Here are the key steps:

  1. Initialize Git:

    • Open your terminal and enter:
      git init
    • This will create a local repository to manage version control in your project.
  2. Initialize npm:

    • To generate a package.json file that records all the project's settings and dependencies, run:
      npm init -y
    • The -y flag accepts the default settings. These settings can be adjusted later according to the needs of the project.

Which dependencies to install for your project?

Once the project is initialized, we must install the dependencies needed to develop and run an Express application with optimization using Webpack and Babel.

  1. Install Express:

    • Express is the framework for web applications in Node.js that simplifies the creation of servers.
    • Use the following command:
      npm install express --save
  2. Install development resources:

    • Webpack and Babel are crucial tools for optimizing and transpiling your code.
    • The following commands install Webpack and its CLI as development dependencies:
      npm install webpack webpack webpack-cli --save-dev
    • For Babel, use:
      npm install @babel/core @babel/preset-env babel-loader --save-dev

How to structure your project?

Organizing code is a professional standard that facilitates work in teams and individual projects. Learn how to organize your project structure:

  1. Create directories and main files:
    • Inside your project, create a folder called src:
      mkdir src
      .
    • Inside src, generate a main file for your application, index.js:
      touch src/index.js

How to set up and run an Express server?

We will set up a basic Express server that can receive requests and return appropriate responses.

  1. Configure Express in index.js:
    const express = require('express');const app = express();
    const port = 3000;
    app.get('/', (req, res) => { res.send('Hello World');});
    app.listen(port, () => { console.log(`Applistening at http://localhost:${port}`);});

This code block performs several tasks:

  • Declares and imports the necessary dependencies.
  • Configures a basic Express application that responds with "Hello World" when accessing the root path(/).
  • Specifies a port on which the application will listen for requests (by default, it uses port 3000).
  1. Run the application:
    • From your terminal, make sure you are in the root directory of your application and run:
      node src/index.js
      .
    • Visit http://localhost:3000 in your browser to verify that the application displays Hello World.

What's next after configuring Express?

The initial setup gives you a basic server running on your local machine. Going forward, we will learn how to integrate Webpack to optimize resource delivery and develop additional features that will improve the performance and modularity of your application. We invite you to continue to improve and explore more possibilities in developing with Express and Webpack. Knowledge is power, and in web development, you never stop learning!

Contributions 5

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Instalación y configuración de Express.js

mkdir webpack-express && cd webpack-express

para inicializar el proyecto:

git init && npm init -y

luego instalamos las dependencias:
Express:

npm install express -S 

Webpack y webpack-cli:

npm install webpack webpack-cli -D

Babel( Transpilar el código de cualquier estandar de ecma a navegadores para su compatibilidad):

npm install @babel/core @babel/preset-env babel-loader

Configuracion del proyecto:

  • creamos la carpeta src, y el archivo dentro de src > index.js

Para escuchar en nuestro server:

node src/index.js

url: localhost:3000 ó el puerto que pusieron.

Actualmente no es necesario ingresar el flag -S para guardar como dependencias de produccion, ya que npm por defecto las guarda de esta forma.

Pero si es necesario el flag -D para aquellas que son solo de desarrollo.

Aun que npm pareca algo sencillo, tiene mucho por dentro, si te animas puedes aprender mas de él en el curso de npm

#nuncaparesdeaprender

Las dependencias de Babel se deberían salvar también como desarrollo:
npm install @babel/core @babel/preset-env babel-loader -D

Hay un pequeño trick que puedes usar para que puedas abrir tu navegador por defecto desde la terminal, y es que cuando muestres el puerto que esta escuchando le agreges una url completa de la siguiente forma:

app.listen(port,()=>{
    console.log(`Server listen at http://localhost:${port}`);
})

Al poner el " http… " tu terminal reconocerá que se trata de una url, y solo bastará con darle click y automaticamente se te abrirá en tu navegador.

Para aquellos que tengan problemas con WSL y no les habrá la ruta en el navegador colocar el host en app.listen()

PORT=3000
HOST:'0,0,0,0'
app.listen(PORT,HOST,()=>console.log(`App listening at localhost${PORT}`))