利用Gulp实现项目自动化部署

​前端项目在部署时一般的操作是运行打包命令,然后通过ftp或者finalShell等工具连接服务器,把dist目录下的文件拖到指定的目录下,完成项目的部署。

 

今天介绍一个实用的工具----gulp,可以让我们省去这一步,实现项目的自动化部署。

 

项目中安装

 

npm i gulp gulp-ssh -save-dev

 

 

目录下新建/gulpConfig/index.js文件

 

const config = {
    "ssh": {
        "test": {
            "host": "100.100.100.xxx",
            "port": "22",
            "username": "root",
            "password": "xxxx"
        },
        "prod": {
            "host": "200.200.200.xxx",
            "port": "22",
            "username": "root",
            "password": "xxxxx"
        }
    }
}

module.exports = config;

 

根目录下新建gulpfile.js

 

var gulp = require("gulp");
var GulpSSH = require("gulp-ssh");
var config = require("./gulpConfig").ssh;
// 需要上传到服务器的路径
const staticPath = "/usr/share/xxxx/xxxxx";

var gulpTestSSH = new GulpSSH({
  ignoreErrors: false,
  sshConfig: config.test,
});

var gulpProdSSH = new GulpSSH({
  ignoreErrors: false,
  sshConfig: config.prod,
});

// 删除test服务器上现有文件...
gulp.task("cleanTest", function() {
  return gulpTestSSH.shell(`rm -rf ${staticPath}`);
});

// 删除prod服务器上现有文件...
gulp.task("cleanProd", function() {
  return gulpProdSSH.shell(`rm -rf ${staticPath}`);
});

// dist 上传文件到test服务器
gulp.task(
  "push-to-test",
  gulp.series("cleanTest", function() {
    return gulp.src(["./dist/**"]).pipe(gulpTestSSH.dest(staticPath));
  })
);

//上传到prod服务器
gulp.task(
  "push-to-prod",
  gulp.series("cleanProd", function() {
    return gulp.src(["./dist/**"]).pipe(gulpProdSSH.dest(staticPath));
  })
);

gulp.task(
  "toTest",
  gulp.series("push-to-test", done => {
    console.log("upload done!");
    done();
  })
);

gulp.task(
  "default",
  gulp.series("push-to-prod", done => {
    console.log("upload done!");
    done();
  })
);

 

package.json里添加gulp命令

 

"scripts": {
    "serve": "vue-cli-service serve --mode dev",
    "build:test": "vue-cli-service build --mode test",
    "build:prod": "vue-cli-service build --mode prod",
    "gulp:prod": "vue-cli-service build --mode prod && gulp",
    "gulp:test": "vue-cli-service build --mode prod && gulp toTest",
    "gulp": "gulp"
  },

 

这里只配置了以下三种命令:

 

打包并上传至测试服务器

 

npm run gulp:test

 

打包并上传至生产服务器

 

npm run gulp:prod

 

把dist目录中的文件上传至生产服务器

 

npm run gulp

 

效果

 

 

自动完成了打包和部署!非常方便!

 

有用的知识又增多了。

 

全栈攻城狮进阶

关注微信公众号,第一时间获取好文章!

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值