Ricerca nel sito web

Come installare ReactJS su Ubuntu 20.04


Questo tutorial esiste per queste versioni del sistema operativo

  • Ubuntu 22.04 (Jammy Jellyfish)
  • Ubuntu 20.04 (Focal Fossa)

Su questa pagina

  1. Prerequisiti
  2. Per iniziare
  3. Installa Node.js
  4. Installa lo strumento Crea app React
  5. Crea la tua prima app React
  6. Crea un file di avvio per l'app React
  7. Configura Nginx per l'app React
  8. Accedi all'interfaccia Web dell'app React
  9. Conclusione

ReactJS è una libreria JavaScript gratuita e open source utilizzata per creare componenti dell'interfaccia utente riutilizzabili. È stato sviluppato da Facebook nel 2011 per creare app Web ricche e coinvolgenti in modo rapido ed efficiente con una codifica minima. Ti permette di creare elementi interattivi sui siti web. Utilizza Virtual DOM che rende l'app veloce. Offre un ricco set di funzionalità tra cui DOM virtuale, associazione dati unidirezionale, componenti, JSX, istruzioni condizionali e molti altri.

In questo tutorial, ti mostreremo come installare l'app create react e ospitare un'applicazione ReactJS con il server web Nginx su Ubuntu 20.04.

Prerequisiti

  • Un server che esegue Ubuntu 20.04 con minimo 2 GB di RAM.
  • Un nome di dominio valido indicato con l'IP del tuo server. In questo tutorial, utilizzeremo il dominio reactjs.example.com.
  • Il server è configurato con una password di root.

Iniziare

Prima di iniziare, si consiglia sempre di aggiornare i pacchetti di sistema all'ultima versione. Puoi aggiornarli eseguendo il seguente comando:

apt-get update -y

Una volta aggiornati tutti i pacchetti, installa le altre dipendenze necessarie eseguendo il seguente comando:

apt-get install curl gnupg2 -y

Una volta installate tutte le dipendenze, puoi procedere al passaggio successivo.

Installa Node.js

Successivamente, dovrai installare Node.js sul tuo server. Per impostazione predefinita, l'ultima versione di Node.js non è disponibile nel repository standard di Ubuntu 20.04. Quindi dovrai installare Node.js dal repository ufficiale di Node.js.

Innanzitutto, aggiungi il repository Node.js con il seguente comando:

curl -sL https://deb.nodesource.com/setup_14.x | bash -

Successivamente, esegui il seguente comando per installare Node.js sul tuo sistema:

apt-get install nodejs -y

Dopo aver installato Node.js, aggiorna NPM alla versione più recente utilizzando il seguente comando:

npm install  -g

Dovresti ottenere il seguente output:

/usr/bin/npm -> /usr/lib/node_modules/npm/bin/npm-cli.js
/usr/bin/npx -> /usr/lib/node_modules/npm/bin/npx-cli.js
+ 
updated 2 packages in 12.78s

Successivamente, verifica la versione installata di Node.js con il seguente comando:

node -v

Dovresti ottenere il seguente output:

v14.15.3

Una volta terminato, puoi procedere al passaggio successivo.

Installa lo strumento Crea app React

Create React App è uno strumento che ti fa risparmiare tempo per l'installazione e la configurazione. Devi solo eseguire un singolo comando e Create React App configurerà tutti gli strumenti necessari per avviare il tuo progetto.

Puoi installare lo strumento Create React App utilizzando il seguente comando:

npm install -g create-react-app

Dovresti ottenere il seguente output:

/usr/bin/create-react-app -> /usr/lib/node_modules/create-react-app/index.js
+ 
added 67 packages from 25 contributors in 4.705s

Una volta terminato, puoi procedere al passaggio successivo.

Crea la tua prima app React

In questa sezione, ti mostreremo come creare un'app React con lo strumento Crea app React.

Innanzitutto, cambia la directory in /opt e crea il tuo primo progetto con il seguente comando:

cd /opt
create-react-app reactproject

Dovresti vedere il seguente output:

Success! Created reactproject at /opt/reactproject
Inside that directory, you can run several commands:

  npm start
    Starts the development server.

  npm run build
    Bundles the app into static files for production.

  npm test
    Starts the test runner.

  npm run eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd reactproject
  npm start

Happy hacking!

Quindi, cambia la directory nel tuo progetto e avvia la tua applicazione con il seguente comando:

cd /opt/reactproject
npm start

Dovresti ottenere il seguente output:

Compiled successfully!

You can now view reactproject in the browser.

  http://localhost:3000

Note that the development build is not optimized.
To create a production build, use npm run build.

Premere CTRL+C per interrompere l'applicazione.

Crea un file di avvio per l'app React

Se desideri avviare l'app React automaticamente al riavvio del sistema, dovrai creare un servizio systemd per la tua app React. Quindi puoi gestire facilmente la tua app usando il comando systemctl. Puoi creare un file di servizio systemd con il seguente comando:

nano /lib/systemd/system/react.service

Aggiungi le seguenti righe:

[Service]
Type=simple
User=root
Restart=on-failure
WorkingDirectory=/opt/reactproject
ExecStart=npm start -- --port=3000

Salva e chiudi il file, quindi ricarica il demone systemd con il seguente comando:

systemctl daemon-reload

Successivamente, avvia il servizio React e abilitalo per l'avvio al riavvio del sistema eseguendo il seguente comando:

systemctl start react
systemctl enable react

Puoi verificare lo stato del servizio React con il seguente comando:

systemctl status react

Dovresti ottenere il seguente output:

? react.service
     Loaded: loaded (/lib/systemd/system/react.service; static; vendor preset: enabled)
     Active: active (running) since Sat 2020-12-19 06:11:42 UTC; 4s ago
   Main PID: 30833 (node)
      Tasks: 30 (limit: 4691)
     Memory: 141.0M
     CGroup: /system.slice/react.service
             ??30833 npm
             ??30844 sh -c react-scripts start "--port=3000"
             ??30845 node /opt/reactproject/node_modules/.bin/react-scripts start --port=3000
             ??30852 /usr/bin/node /opt/reactproject/node_modules/react-scripts/scripts/start.js --port=3000

Dec 19 06:11:42 ubunt4 systemd[1]: Started react.service.
Dec 19 06:11:43 ubunt4 npm[30833]: >  start /opt/reactproject
Dec 19 06:11:43 ubunt4 npm[30833]: > react-scripts start "--port=3000"
Dec 19 06:11:46 ubunt4 npm[30852]: ? ?wds?: Project is running at http://0.0.0.0:3000/
Dec 19 06:11:46 ubunt4 npm[30852]: ? ?wds?: webpack output is served from
Dec 19 06:11:46 ubunt4 npm[30852]: ? ?wds?: Content not from webpack is served from /opt/reactproject/public
Dec 19 06:11:46 ubunt4 npm[30852]: ? ?wds?: 404s will fallback to /
Dec 19 06:11:46 ubunt4 npm[30852]: Starting the development server...

Una volta terminato, puoi procedere al passaggio successivo.

Configura Nginx per l'app React

È una buona idea installare e configurare Nginx come proxy inverso per l'app React. Quindi puoi accedere alla tua app attraverso la porta 80.

Innanzitutto, installa il pacchetto Nginx utilizzando il seguente comando:

apt-get install nginx -y

Una volta installato Nginx, crea un nuovo file di configurazione dell'host virtuale Nginx:

nano /etc/nginx/sites-available/reactjs.conf

Aggiungi le seguenti righe:

upstream backend {
  server localhost:3000;
}

server {
    listen 80;
    server_name reactjs.example.com;

    location / {
        proxy_pass http://backend/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;

        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forward-Proto http;
        proxy_set_header X-Nginx-Proxy true;

        proxy_redirect off;
    }
}

Salva e chiudi il file, quindi abilita l'host virtuale Nginx con il seguente comando:

ln -s /etc/nginx/sites-available/reactjs.conf /etc/nginx/sites-enabled/

Successivamente, verifica Nginx per eventuali errori di sintassi eseguendo il seguente comando:

nginx -t

Dovresti ottenere il seguente output:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Infine, riavvia il servizio Nginx per applicare le modifiche:

systemctl restart nginx

Puoi anche verificare lo stato del servizio Nginx con il seguente comando:

systemctl status nginx

Dovresti vedere il seguente output:

? nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: active (running) since Sat 2020-12-19 06:12:42 UTC; 4s ago
       Docs: man:nginx(8)
    Process: 30899 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 30913 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
   Main PID: 30915 (nginx)
      Tasks: 3 (limit: 4691)
     Memory: 3.6M
     CGroup: /system.slice/nginx.service
             ??30915 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
             ??30916 nginx: worker process
             ??30917 nginx: worker process

Dec 19 06:12:42 ubunt4 systemd[1]: Starting A high performance web server and a reverse proxy server...
Dec 19 06:12:42 ubunt4 systemd[1]: Started A high performance web server and a reverse proxy server.

A questo punto, Nginx è installato e configurato per servire l'app React. Ora puoi procedere al passaggio successivo.

Accedi all'interfaccia Web dell'app React

Ora apri il tuo browser web e digita l'URL http://reactjs.example.com. Verrai reindirizzato all'interfaccia web di React.Js nella seguente schermata:

Conclusione

Congratulazioni! hai installato e configurato correttamente React.Js sul server Ubuntu 20.04. Spero che ora tu abbia abbastanza conoscenze per distribuire la tua applicazione React nell'ambiente di produzione. Non esitate a chiedermi se avete domande.