欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue项目自动打包部署到七牛

程序员文章站 2024-01-12 13:07:28
...

1、在package.json同级文件下,新建三个js文件
upload-qiniu.js delect-qiniu.js refresh-qiniu-CDN.js
vue项目自动打包部署到七牛
2、新建一个js文件存放七牛的key和**
vue项目自动打包部署到七牛
3、 upload-qiniu.js 中的 var bucketName = "app-customer"对应的就是下面的域名
vue项目自动打包部署到七牛

const qnKey = require('./src/utils/key'); // 对应刚创建的key.js文件路径
const qiniu = require('qiniu');
const path = require('path')
const fs = require("fs");
const exec = require('child_process').exec;

exports.func = function () {
    //递归读取文件
    function readFileList(dir, filesList = []) {
        const files = fs.readdirSync(dir);
        files.forEach((item, index) => {
            var fullPath = path.join(dir, item);
            const stat = fs.statSync(fullPath);
            if (stat.isDirectory()) {
                readFileList(path.join(dir, item), filesList);
            } else {
                filesList.push(fullPath);
            }
        });

        return filesList;
    }

    var buildPath = __dirname + "\\dist\\";   // 这是npm run build 打包生成的dist文件夹爱
    var filesList = [];
    readFileList(buildPath, filesList);

    var bucketName = "app-customer"  // 这是上传到的七牛bucket名
    var mac = new qiniu.auth.digest.Mac(qnKey.accessKey, qnKey.secretKey);

    String.prototype.replaceAll = function (s1, s2) {
        return this.replace(new RegExp(s1, "gm"), s2);
    }
    for (let i = 0; i < filesList.length; i++) {

        var localFile = filesList[i];
        var key = "mcd/" + localFile.replace(buildPath, "").replaceAll("\\\\", "/");

        var options = {
            scope: bucketName + ":" + key,
            expires: 120,
            returnBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'
        };
        var putPolicy = new qiniu.rs.PutPolicy(options);
        var uploadToken = putPolicy.uploadToken(mac);

        var config = new qiniu.conf.Config();
        // 空间对应的机房
        config.zone = qiniu.zone.Zone_z0;
        config.useCdnDomain = true;
        var formUploader = new qiniu.form_up.FormUploader(config);
        var putExtra = new qiniu.form_up.PutExtra();

        // 文件上传
        formUploader.putFile(uploadToken, key, localFile, putExtra, function (respErr,
            respBody, respInfo) {
            if (respErr) {
                throw respErr;
            }
            if (respInfo.statusCode == 200) {
                //console.log(respBody);
                console.log('%c 上传文件成功: %o', 'color:green', respBody.key);
            } else {
                //console.log(respInfo.statusCode);
                //console.log(respBody);
                console.log('%c 上传文件失败: %o', 'color:red', respBody.key);
            }
        });
    }
}

4、 delect-qiniu.js

const qnKey = require('./src/utils/key');
const qiniu = require('qiniu');
const qnupload = require('./upload-qiniu')

var mac = new qiniu.auth.digest.Mac(qnKey.accessKey, qnKey.secretKey);
var config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z0;
var bucketManager = new qiniu.rs.BucketManager(mac, config);

var bucketName = "app-customer";

// @param options 列举操作的可选参数
//                prefix    列举的文件前缀
//                marker    上一次列举返回的位置标记,作为本次列举的起点信息
//                limit     每次返回的最大列举文件数量
//                delimiter 指定目录分隔符
var options = {
    limit: 10,
    prefix: 'mcd/static/',
};
var deleteFileKeys = [];

function GetDelectList(backet, o, callback) {
    bucketManager.listPrefix(backet, o, function (err, respBody, respInfo) {
        if (err) {
            console.log(err);
            throw err;
        }
        if (respInfo.statusCode == 200) {
            //如果这个nextMarker不为空,那么还有未列举完毕的文件列表,下次调用listPrefix的时候,
            //指定options里面的marker为这个值
            var nextMarker = respBody.marker;
            // var commonPrefixes = respBody.commonPrefixes;
            // console.log(nextMarker);
            // console.log(commonPrefixes);
            var items = respBody.items;
            items.forEach(function (item) {
                deleteFileKeys.push(item.key);
            });
            if (nextMarker) {
                o.marker = nextMarker;
                GetDelectList(backet, o, callback);
            } else {
                callback();
                deleteFileKeys = [];
            }
        } else {
            console.log(respInfo.statusCode);
            // console.log(respBody);
        }
    });
}

function DelectFiles(bucket, dels, callback) {
    //每个operations的数量不可以超过1000个,如果总数量超过1000,需要分批发送
    var deleteOperations = [];
    for (let i = 0; i < dels.length; i++) {
        deleteOperations.push(qiniu.rs.deleteOp(bucket, dels[i]));
    }
    bucketManager.batch(deleteOperations, function (err, respBody, respInfo) {
        if (err) {
            console.log(err);
            //throw err;
        } else {
            if (parseInt(respInfo.statusCode / 100) == 2) {
                respBody.forEach(function (item) {
                    // if (item.code == 200) {
                    //     console.log('%c 删除文件成功', 'color:green');
                    // } else {
                    //     console.log('%c 删除文件失败', 'color:red');
                    // }
                });
                console.log(' %c 删除文件成功', 'color:green');
            } else {
                // console.log(respInfo.deleteusCode);
                // console.log(respBody);
                console.log(' %c 删除文件失败', 'color:red');
            }
            callback();
        }
    });
}

//获取删除列表
GetDelectList(bucketName, options, () => {
    // deleteFileKeys.push('index.html');
    // deleteFileKeys.push('favicon.ico');
    //根据删除列表删除文件
    DelectFiles(bucketName, deleteFileKeys, () => {
        //上传新文件
        qnupload.func();
    });
});

5、refresh-qiniu-CDN.js

const qiniu = require('qiniu');
const qnKey = require('./src/utils/key.js');

var mac = new qiniu.auth.digest.Mac(qnKey.accessKey, qnKey.secretKey);
var cdnManager = new qiniu.cdn.CdnManager(mac);

//URL 列表 刷新线上地址的文件
var urlsToRefresh = [
    'http://web.armark.com.cn/mcd/index.html',
    'http://web.armark.com.cn/mcd/favicon.ico'
];

//刷新链接,单次请求链接不可以超过100个,如果超过,请分批发送请求
cdnManager.refreshUrls(urlsToRefresh, function (err, respBody, respInfo) {
    if (err) {
        throw err;

    }
    // console.log(respInfo);
    // console.log(respBody);
    if (respInfo.statusCode == 200) {
        var jsonBody = respBody;
        // console.log(jsonBody.code);
        console.log(jsonBody.error);
        // console.log(jsonBody.requestId);
        // console.log(jsonBody.invalidUrls);
        // console.log(jsonBody.invalidDirs);
        // console.log(jsonBody.urlQuotaDay);
        // console.log(jsonBody.urlSurplusDay);
        // console.log(jsonBody.dirQuotaDay);
        // console.log(jsonBody.dirSurplusDay);-
        console.log("刷新CDN成功!");
    } else {
        console.log("刷新CDN失败!");
    }
});

6、最后在package.json文件夹下添加下面的命令
“build-re”: “vue-cli-service build && node ./delect-qiniu.js && node ./refresh-qiniu-CDN.js”,
然后运行一下npm run build-re就可以了,他会自动打包生成新的dist文件夹并上传到七牛然后刷新
vue项目自动打包部署到七牛

相关标签: 自动打包 vue