美文网首页
【React】打包部署

【React】打包部署

作者: 24c41111e47b | 来源:发表于2023-11-01 16:50 被阅读0次

    思路:
    使用打包工具打包,生成网页静态资源文件目录,将资源目录压缩上传到指定服务器目录,服务器配置nginx访问静态资源目录


    部署脚本

    #!/bin/bash
    # 参考:# https://spike-leung.github.io/blog/others/simple-deploy-static-file.html#%E5%8E%8B%E7%BC%A9
    # 使用方法:
    # step1: 将该脚本放在工程的根目录下(跟package.json文件同级)
    # step2: 根据情况修改下面的参数
    # step3: 打开终端,执行脚本。(输入sh ,然后将脚本文件拉到终端,会生成文件路径,然后enter就可)
    # exp:
    # ```
    # ./deploy
    # ```
    
    # ======================= 参数配置区域 =====================
    # 服务地址
    host="root@1x.20x.x8.xx"
    
    # 项目名(最终的解压名)
    proj="hellow-react"
    
    # 部署路径
    deploy_path="/home/ubuntu/web/${proj}"
    
    # 密钥路径(部分服务器需要使用密钥登录)
    secret_key="$HOME/Desktop/xxx/LightsailDefaultKey-ap-northeast-2.pem"
    
    # ======================= 自动脚本区域 =====================
    # abort on errors
    set -e
    
    # install 更新依赖
    yarn
    
    # build 构建
    yarn build
    
    echo "Build finish!"
    
    # navigate into the build output directory
    cd build/
    
        echo "tar start"
    
    # 打包压缩构建后的静态文件
    tar zcvf build.tar.gz *
    
    echo "tar finish"
    
    echo 'upload to 13.209.18.66 and untar'
    
    # 检查目标机器是否存在部署路径
    ssh -i ${secret_key} $host "rm -rf ${deploy_path}"
    ssh -i ${secret_key} $host "mkdir ${deploy_path}"
    
    # 上传tar包到目标机器,并解压到对应的目录
    # ssh root@1.1.1.1 "tar -C /home/hello-world -xz -f-" < build.tar.gz
    # 亚马逊服务需要使用密钥登录
    ssh -i ${secret_key} $host "tar -C ${deploy_path} -xz -f-" < build.tar.gz
    
    echo 'upload & untar done'
    
    cd -
    

    1.复制上面的脚本,放入工程根目录命名为 deploy.sh,修改参数配置为自己的项目配置即可

    2.执行构建资源命令 yarn build

    3.执行发布部署脚本 sh deploy.sh

    nginx安装

    参照 链接 完成ubuntu环境下的nginx安装

    nginx配置

    安装好了nginx以后,就可以配置nginx的配置文件,指定前面部署的网页资源进行访问工作,nginx支持分模块设置配置文件(不同的配置文件名机制), 这里我们为了方便来修改默认的配置文件 default

    进入配置文件目录:
    cd /etc/nginx/sites-available

    打开配置文件:
    sudo vim default

    修改配置文件:

    # 修改为自己的项目路径
    root /home/xxx/hello-world;
    

    重启nginx

    sudo service nginx restart
    或
    sudo systemctl restart nginx
    
    

    浏览器直接访问nginx所在服务的ip或者域名即可(默认端口80)

    到这里我们的服务就发布完成了

    错误处理

    访问 xxx.xxx.xx/path/login 路径报错404

    修改nginx路径配置:

    location / {
        #try_files $uri $uri/ =404;
        修改为
        try_files $uri $uri/ /index.html
    }
    

    参考

    部署前端静态资源
    nginx安装
    nginx启动/停止/重启

    相关文章

      网友评论

          本文标题:【React】打包部署

          本文链接:https://www.haomeiwen.com/subject/rdkgidtx.html