5分钟学习React

本文的主线 定义 => 安装 => 开发 => 打包 => 部署

定义

React是什么?

  • React是一个Web前端开发框架

安装

首先 安装Node.js环境

1
2
3
4
5
6
7
8
9
10
node -v
# v14.17.3

npm -v
# 6.14.13

npm install -g cnpm --registry=https://registry.npm.taobao.org

cnpm -v
# cnpm@7.0.0

然后 安装create-react-app => 用于创建React项目

1
2
3
4
cnpm install -g create-react-app

create-react-app -V
# 4.0.3

开发

首先 创建React项目

1
2
3
4
5
6
7
8
npm config set registry https://registry.npm.taobao.org

npm config get registry
# https://registry.npm.taobao.org/

create-react-app react-demo

cd react-demo

接着 启动React项目

1
npm start

最后 使用浏览器打开http://localhost:3000/ => 页面如下图

learn-react-in-5-minutes-01.png

打包

1
2
3
4
npm run build

ls build
# asset-manifest.json favicon.ico index.html logo192.png logo512.png manifest.json robots.txt static

部署

首先 安装和配置Nginx => 基于Ubuntu 1804 Server

1
2
3
sudo apt install -y nginx

sudo vim /etc/nginx/sites-enabled/react-demo.conf
1
2
3
4
5
6
7
8
9
server {
listen 80;
server_name react-demo.com;

location / {
root /opt/sites/react-demo/build;
try_files $uri $uri/ /index.html?$query_string;
}
}

然后 确认Nginx配置成功 并重新加载配置以生效

1
2
3
4
5
sudo nginx -t
# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful

sudo nginx -s reload

最后 使用浏览器打开http://react-demo.com/ => 注意修改hosts解析域名至该服务IP