如何使用NodeJS后端开发和构建React App — Typescript版本

There are so many ways we can build React apps and ship for production. One way is to build the React app with NodeJS or Java and another way is to build the angular and serve that static content with NGINX web server. With NodeJS we have to deal with the server code as well, for example, you need to load index.html page with node.

我们有很多方法可以构建React应用并交付生产。 一种方法是使用NodeJS或Java构建React应用,另一种方法是使用NGINX Web服务器构建angular并提供静态内容。 使用NodeJS,我们还必须处理服务器代码,例如,您需要使用node加载index.html页面。

In this post, we will see the details and implementation with the NodeJS. We will go through step by step with an example.

在本文中,我们将看到NodeJS的详细信息和实现。 我们将逐步举例。

  • Introduction

    介绍

  • Prerequisites

    先决条件

  • Example Project

    示例项目

  • Just Enough NodeJS For This Project

    就足够这个项目的NodeJS

  • Development Phase

    开发阶段

  • How To Build Project For Production

    如何建立生产项目

  • How To Package Project For Production

    如何打包生产项目

  • Summary

    摘要

  • Conclusion

    结论

介绍 (Introduction)

React is a javascript library for building web apps and it doesn’t load itself in the browser. We need some kind of mechanism that loads the index.html (single page) of React application with all the dependencies(CSS and js files) in the browser. In this case, we are using node as the webserver which loads React assets and accepts any API calls from the React UI app.

React是一个用于构建Web应用程序JavaScript库,它不会在浏览器中加载自身。 我们需要某种机制来加载带有浏览器中所有依赖项(CSS和js文件)的React应用程序的index.html (单页)。 在这种情况下,我们使用节点作为Web服务器,以加载React资产并接受来自React UI应用程序的所有API调用。

Image for post
React With NodeJS 与NodeJSReact

If you look at the above diagram all the web requests without the /api will go to React routing and the React Router kicks in and loads components based on the path. All the paths that contain /api will be handled by the Node server itself.

如果您查看上图,所有不带/ api的Web请求都将进入React路由,React Router随即启动并根据路径加载组件。 包含/ api的所有路径都将由节点服务器本身处理。

In this post, we are going to develop the React app with NodeJS (Written in Typescript) and see how to build for production.

在本文中,我们将使用NodeJS(用Typescript编写)开发React应用,并了解如何为生产而构建。

先决条件 (Prerequisites)

There are some prerequisites for this article. You need to have nodejs installed on your laptop and know-how http works. If you want to practice and run this on your laptop you need to have these on your machine.

本文有一些先决条件。 您需要在笔记本电脑上安装Node.js并了解HTTP的工作原理。 如果要在笔记本电脑上练习并运行此程序,则需要在计算机上安装它们。

Here is the complete guide on how to develop a React app with nodejs as a backend server. If you are not familiar with the process or you want to know before studying this guide, I would recommend you going through it.

这是有关如何使用nodejs作为后端服务器开发React应用的完整指南。 如果您不熟悉此过程,或者想在学习本指南之前先了解一下,建议您仔细阅读。

Javascript版本 (Javascript Version)

How To Develop and Build React App With NodeJS

如何使用NodeJS开发和构建React App

示例项目 (Example Project)

This is a simple project which demonstrates developing and running React application with NodeJS. We have a simple app in which we can add users, count, and display them at the side, and retrieve them whenever you want.

这是一个简单的项目,演示了如何使用NodeJS开发和运行React应用程序。 我们有一个简单的应用程序,可以在其中添加用户,计数并在侧面显示它们,并在需要时检索它们。

Image for post
Example Project 示例项目

As you add users we are making an API call to the nodejs server to store them and get the same data from the server when we retrieve them. You can see network calls in the following video.

添加用户时,我们正在对nodejs服务器进行API调用以存储它们,并在我们检索用户时从服务器获取相同的数据。 您可以在以下视频中看到网络通话。

Image for post
API network calls API网络调用

Here is a Github link to this project. You can clone it and run it on your machine.

这是该项目的Github链接。 您可以克隆它并在您的计算机上运行它。

// clone the project
git clone https://github.com/bbachi/react-nodejs-typescript-example.git// React Code
cd my-app
npm install
npm start// API code
cd api
npm install
npm run start:dev

就足够这个项目的NodeJS (Just Enough NodeJS For This Project)

If you are new to NodeJS don’t worry this short description is enough to get you started with this project. If you are already aware of NodeJS, you can skip this section.

如果您是NodeJS的新手,请不要担心,这段简短的说明足以让您开始使用此项目。 如果您已经知道NodeJS,则可以跳过本节。

NodeJS is an asynchronous event-driven javascript runtime environment for server-side applications. The current version of the nodejs is 12 and you can install it from this link here. You can click on any LTS link and the NodeJS package is downloaded and you can install it on your laptop.

NodeJS是用于服务器端应用程序的异步事件驱动的javascript运行时环境。 当前的nodejs版本是12 ,您可以在此链接中安装它 您可以单击任何LTS链接,然后下载NodeJS软件包,然后将其安装在笔记本电脑上。

You can check the version of the Node with this command node -v. You can run javascript on the node REPL by typing the command node on the CLI.

您可以使用此命令node -v.检查Node的版本node -v. 您可以通过在CLI上键入命令node在节点REPL上运行javascript。

Image for post
Typing commands on REPL 在REPL上键入命令

The installation of a node is completed and you know how to run javascript. You can even run javascript files. For example, Let’s put the above commands in the sample.js file and run it with this command node sample.js.

节点的安装已完成,您知道如何运行javascript。 您甚至可以运行javascript文件。 例如,让我们将以上命令放入sample.js文件,并使用此命令node sample.js.运行它node sample.js.

sample.js sample.js

开发阶段 (Development Phase)

Usually, the way you develop and the way you build and run in production are completely different. Thatswhy, I would like to define two phases: Development phase and Production phase.

通常,您的开发方式以及在生产中构建和运行的方式是完全不同的。 因此,我想定义两个阶段:开发阶段和生产阶段。

In the development phase, we run the nodejs server and the React app on completely different ports. It’s easier and faster to develop that way. If you look at the following diagram the React app is running on port 3000 with the help of a webpack dev server and the nodejs server is running on port 3080.

在开发阶段,我们在完全不同的端口上运行nodejs服务器和React应用程序 这样开发起来更容易,更快捷。 如果您查看下图,则在Webpack开发服务器的帮助下,React应用程序在端口3000上运行,而nodejs服务器在端口3080上运行。

Image for post
Development Environment 开发环境

项目结构 (Project Structure)

Let’s understand the project structure for this project. We will have two package.json: one for the React and another for nodejs API. It’s always best practice to have completely different node_modules for each one. In this way, you won’t get merging issues or any other problems regarding web and server node modules collision.

让我们了解该项目的项目结构。 我们将有两个package.json:一个用于React ,另一个用于nodejs API 。 始终最好的做法是每个节点都有完全不同的node_modules。 这样,您将不会遇到合并问题或有关Web和服务器节点模块冲突的任何其他问题。

Image for post
Project Structure 项目结构

If you look at the above project structure, all the React app resides under the my-app folder and nodejs API resides under the api folder.

如果您查看上述项目结构,则所有React应用程序都位于my-app文件夹下,而nodejs API则位于api文件夹下。

NodeJS API (NodeJS API)

We use the express and nodemon on the server-side. Express is the Fast, unopinionated, minimalist web framework for NodeJS and nodemon is the library which makes your API reloads automatically whenever there is a change in the files. Let’s install these two dependencies. nodemon is only used for development so install this as a dev dependency.

我们在服务器端使用express和nodemon。 Express是用于NodeJS的快速,不受限制的,极简的Web框架,而nodemon是一个库,该库可以使您的API在文件发生更改时自动重新加载。 让我们安装这两个依赖项。 nodemon仅用于开发,因此请将其安装为dev依赖项。

Since it is written in typescript you need some other dependencies as well. Let’s install all the dependencies.

由于它是用打字稿编写的,因此您还需要一些其他依赖项。 让我们安装所有依赖项。

npm install express --save
npm install @types/express nodemon ts-node typescript --save-dev
npm install webpack webpack-cli --save-dev

Here is the package.json of nodejs API.

这是nodejs API的package.json

package.json package.json

We need to import express and define two routes: /api/users and /api/user and the server listening on the port 3080. Here are the app.ts, routes.ts, user.ts files. We use body-parser to handle data in the http request object.

我们需要导入express并定义两个路由: / api / users/ api / user以及侦听端口3080的服务器这是app.ts,routes.ts和user.ts文件。 我们使用body-parser处理http请求对象中的数据。

API files API文件

We are using nodemon in the development environment. Here is the configuration nodemon.json file. Any file that ends with ts will be watched and all the node_modules are ignored.

我们在开发环境中使用nodemon。 这是配置nodemon.json文件。 任何以ts结尾的文件都会被监视,所有的node_modules都会被忽略。

nodemon.json nodemon.json

You need to start the nodejs API with this command npm run start:devand the moment you change any file, the server will be automatically restarted.

您需要使用此命令npm run start:dev启动nodejs API,并且在更改任何文件时,服务器将自动重启。

Image for post
Development Environment 开发环境

ReactUI (React UI)

Now the nodejs API is running on port 3080. Now it’s time to look at the React UI. The entire React app is under the folder my-app. You can create with this command npx create-react-app my-appI am not going to put all the files here you can look at the entire files in the above Github link or here.

现在,nodejs API在端口3080上运行。现在是时候查看React UI。 整个React应用程序都在文件夹my-app下。 您可以使用此命令npx create-react-app my-app我不会将所有文件放在此处,您可以在上面的Github链接或此处查看整个文件

Let’s see some important files here. Here is the service file which calls node API. This is a service file with two async functions that use fetch API to make the API calls.

让我们在这里看到一些重要的文件。 这是调用节点API的服务文件。 这是一个具有两个异步函数的服务文件,这些函数使用访存API进行API调用。

UserService.js UserService.js

Here is the app component that calls this service and gets the data from the API. Once we get the data from the API we set the state accordingly and renders the appropriate components again to pass the data down the component tree. You can find other components here.

这是调用此服务并从API获取数据的应用程序组件。 从API获取数据后,我们将相应地设置状态,并再次渲染适当的组件以将数据传递到组件树。 您可以在此处找到其他组件。

App.js App.js

React UI和Node API之间的交互 (Interaction between React UI and Node API)

In the development phase, the React app is running on port 3000 with the help of a create-react-app and nodejs API running on port 3080.

在开发阶段,React应用程序在端口3080上运行的create-react-app和nodejs API的帮助下在端口3000上运行。

There should be some interaction between these two. We can proxy all the API calls to nodejs API. Create-react-app provides some inbuilt functionality and to tell the development server to proxy any unknown requests to your API server in development, add a proxy field to your package.json of the React. Have a look at the below package.json below. Remember you need to put this in the React UI package.json file.

两者之间应该有一些互动。 我们可以将所有API调用代理到nodejs API。 Create-react-app提供了一些内置功能,并告诉开发服务器将任何未知请求代理到开发中的API服务器,请在React的package.json中添加一个proxy字段。 看看下面下面的package.json。 请记住,您需要将其放入React UI package.json文件中。

package.json package.json

With this in place, all the calls start with /api will be redirected to http://localhost:3080 where the nodejs API running.

有了这个,所有以/ api开头的调用将被重定向到http:// localhost:3080 运行nodejs API的位置。

Once this is configured, you can run the React app on port 3000 and nodejs API on 3080 still make them work together.

配置完成后,您可以在端口3000上运行React应用,而3080上的nodejs API仍然可以使它们协同工作。

// nodejs API (Terminal 1)cd api (change it to API directory)
npm run start:dev// React app (Terminal 2)cd my-app (change it to app directory)
npm start

如何建立生产项目 (How To Build Project For Production)

The React app runs on the port 3000 with the help of a create-react-app. This is not the case for running in production. We have to build the React project and load those static assets with the node server. Let’s see those step by step here.

React应用程序在create-react-app的帮助下在端口3000上运行。 在生产中运行不是这种情况。 我们必须构建React项目,并用节点服务器加载这些静态资产。 让我们逐步了解这些内容。

First, we need to build the React project with this command npm run build and all the built assets will be put under the build folder.

首先,我们需要使用此命令npm run build来构建React项目,所有构建的资产都将放置在build文件夹下。

Image for post
npm run build npm运行构建

Second, we need to make some changes on the server-side. Here is the modified app.ts file.

其次,我们需要在服务器端进行一些更改。 这是修改后的app.ts文件。

  1. We have to use express.static at line number 27 to let express know there are a dist folder and assets of the Angular build.

    我们必须在第27行使用express.static来使express知道有dist文件夹和Angular构建的资产。

  2. Load index.html for the default route / at line number 33

    在第33行加载index.html作为默认路由/

app.ts 应用程序

Once you are done with the above changes, you can actually run the whole app with the nodejs server running on port 3080 like below as nodejs acts as a web server as well.

完成上述更改后,您实际上可以使用运行在端口3080上的nodejs服务器运行整个应用程序,如下所示,因为nodejs也可以充当Web服务器。

Image for post
The whole app running on the port 3080 整个应用程序在端口3080上运行

如何打包生产项目 (How To Package Project For Production)

Packaging this application for production needs other tools such as webpack, gulp. We need a webpack to transpile the NodeJS API into javascript and bundle it in a single server file.

打包此应用程序以进行生产需要其他工具,例如webpack,gulp。 我们需要一个webpack将NodeJS API转换为javascript并将其捆绑在一个服务器文件中。

We use the gulp tool to copy all the built files and put them in the appropriate folders and finally make them a deployable artifact or zip file.

我们使用gulp工具复制所有构建的文件,并将它们放置在适当的文件夹中,最后使它们成为可部署的工件或zip文件。

摘要 (Summary)

  • There are so many ways we can build React apps and ship for production.

    我们有很多方法可以构建React应用并交付生产。
  • One way is to build React with NodeJS.

    一种方法是使用NodeJS构建React。
  • We have seen how to build the NodeJS API in typescript version

    我们已经看到了如何在打字稿版本中构建NodeJS API
  • In the development phase, we can run React and Nodejs on separate ports. React on 3000 and NodeJS server on port 3080.

    在开发阶段,我们可以在单独的端口上运行React和Nodejs。 在端口3080上对3000和NodeJS服务器进行React。

  • The interaction between these two happens with proxying all the calls to API.

    这两者之间的交互是通过代理所有对API的调用而发生的。
  • In the production phase, you can build the React app and put all the assets in the build folder and load it with the node server.

    在生产阶段,您可以构建React应用并将所有资产放入build文件夹中,然后将其加载到节点服务器中。
  • Nodejs act as a web server as well in the above case. You need to let express know where are all the React assets are.

    在上述情况下,Node.js也充当Web服务器。 您需要让Express知道所有React资产在哪里。
  • We can package the application in a number of ways.

    我们可以通过多种方式打包应用程序。
  • You can deploy the packaged zip folder in any node environment.

    您可以在任何节点环境中部署打包的zip文件夹。

结论 (Conclusion)

This is one way of building and shipping React apps. This is really useful when you want to do server-side rendering or you need to do some processing. NodeJS is non-blocking IO and it is very good for normal websites as well. In future posts, I will discuss more on deploying strategies for this kind of architecture.

这是构建和交付React应用程序的一种方式。 当您要执行服务器端渲染或需要进行一些处理时,这非常有用。 NodeJS是非阻塞IO,对于普通网站也非常有用。 在以后的文章中,我将讨论有关这种架构的部署策略的更多信息。

翻译自: https://medium.com/bb-tutorials-and-thoughts/how-to-develop-and-build-react-app-with-nodejs-backend-typescript-version-27a6a283a7c5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值