使用 gulp-sftp 快速部署 Vue 项目

1,412 阅读1分钟



使用vue开发单页应用项目有点多,每次 build 完都要通过 ftp 上传到服务器很麻烦。我希望打包完成之后可以自动提交到服务器静态文件存放位置。 


业务需求

vue项目构建完成后会在项目根目录生成一个 dist/ 目录,只需要将该目录下的文件上传到服务器的web容器即可访问。我们要做的就是通过命令行将 dist/ 目录下所有文件上传到服务器对应的目录下。 

实现步骤 

  1. 安装gulp和gulp-sftp 

    $ yarn add gulp gulp-sftp --dev
  2. 在项目根目录新建 gulp 配置文件 gulpfile.js 

    const gulp = require('gulp');
    // npm下载的gulp-sftp存在pipe is not a function需要修改其目录下的index.js
    const ftp = require('./src/assets/gulp-sftp/index.copy.js');
    
    // 是上传地址配置,可以在.gitignore中忽略此文件上传,为了安全本地拥有就可以了
    const config = require('./serveConfig');
    
    /**
     * 自动部署到服务器
     */
    gulp.task('upload', function () {
        console.log('## 正在部署到服务器上')
        let configOption = process.argv[ 3 ].split( '--' );
        return gulp.src('.' + config.publicPath + '**')
            .pipe( ftp( config[ configOption[ 1 ] ] ) );
    });
  3. 由于gulp-sftpnpm 库存在一定问题,需要手动更改 index.js ,为了让同事下载依赖的时候不遇到这个问题,提取 node_modules 下的 gulp-sftp/src/assets/ 下,复制index.js 命名为 index.copy.js 。找到:

    file.pipe(stream); // start upload
     它应该在 index.js 的 284 行,更改为:
    // start upload
    if ( file.isStream() ) {
        file.contents.pipe( stream );
    } else if ( file.isBuffer() ) {
        stream.end( file.contents );
    }
  4. 创建 gulp-sftp 配置文件 serveConfig.js

     module.exports = {
        // 部署到测试服务器上
        devTest: {
            // 部署到服务器的路径
            remotePath: '/data/',
            // ip地址
            host: 'x.x.x.x',
            // 帐号
            user: '***',
            // 密码
            pass: '***',
            // 端口
            port: 22
        },
        devDist: { //部署正式服务器上
            // 部署到服务器的路径
            remotePath: '/data/',
            // ip地址
            host: 'x.x.x.x',
            // 帐号
            user: '***',
            // 密码
            pass: '***',
            // 端口
            port: 22
        },
        publicPath: '/dist/' //程序编译好路径
    };
  5. 至此我们可以使用 gulp 来执行定义的上传任务了

    $ gulp upload --devTest
  6. 为了方便我们构建完成后自动上传可以在 package.json 中定义两个命令

    "test": "vue-cli-service build && gulp upload --devTest",
    "prod": "vue-cli-service build && gulp upload --devDist"