前端vue/react使用构建工具打包后自动部署到服务器

Jiafeng

分类: Nodejs、React、Vue 385 0

前言

  • 首先打包编译生成一系列的静态文件(dist),然后把这些文件放到服务器的指定目录中,放完之后配置nginx指向到你存放静态资源的目录,完成nginx指向才能保证请求能访问到相应的资源。这样就存在个问题,每次修改完成,都需要手动上传到指定服务器目录,比较费时费力,下面介绍两种插件自动上传。

ftp连接方式

  1. 安装ftp-deploy:yarn add ftp-deploy --dev
  2. package.json的scripts添加:"upload": "vue-cli-service build && node pushFtp.js"
    // pushFtp.js
    const FtpDeploy = require('ftp-deploy');
    const ftpServ = new FtpDeploy();
    let config = {
    user: 'xxxxxx', // 用户名
    password: 'xxxxxx', // 密码
    host: 'xx.xx.xx.xx', // ftp 主机地址
    port: 21, // 端口
    localRoot: __dirname + '/dist', // 本地资源路径
    remoteRoot: '/pages/dist/', // 远程资源路径
    include: ['*', '**/*'], // 包含文件
    exclude: ['dist/**/*.map'], // 排除文件
    deleteRemote: true // 上传前是否删除
    };
    // 上传完成后回调
    ftpServ.deploy(config)
    .then(res => { // 上传成功
        console.log('finished:', res);
        return false;
    })
    .catch(err => { // 上传失败
        console.log(err);
        return false;
    });

sftp连接方式

  1. 安装ssh2-sftp-client:yarn add ssh2-sftp-client --dev
  2. package.json的scripts添加:"upload": "vue-cli-service build && node pushSftp.js"
    // pushSftp.js
    const Client = require('ssh2-sftp-client')
    const config = {
    path: {
        romotePath: '/opt/dist-center',// 远程资源路径自定义
        localPath: __dirname + '/dist' // 本地资源路径
    },
    romote: {
        host: 'xx.xx.xx.xx',// sftp 主机地址
        port: 22,
        username: 'xxxxxx',// 用户名
        password: 'xxxxxx',// 用户密码
    }
    }
    function main(localPath, romotePath) {
    // 实例化
    const sftp = new Client()
    sftp
        .connect(config.romote)
        .then(() => {
            console.log('连接成功,删除原有文件...')
            return sftp.rmdir(romotePath, true)
        })
        .then(() => {
            console.log('上传中...')
            return sftp.uploadDir(localPath, romotePath)
        })
        .catch(err => {
            console.log('出错了!')
            console.log(err)
        })
        .finally(() => {
            console.log('完成!');
            // 断开连接
            sftp.end()
        })
    }
    main(
    config.path.localPath,
    config.path.romotePath,
    )
  • 1人 Love
  • 0人 Haha
  • 0人 Wow
  • 0人 Sad
  • 0人 Angry
nodejs

作者简介: Jiafeng

共 0 条评论关于 “前端vue/react使用构建工具打包后自动部署到服务器”

Loading...