-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
102 lines (88 loc) · 3.05 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**!
* 上传webpack编译后的文件到阿里云OSS
*
* @author mfylee@163.com
* @since 2017-08-23
*/
var fs = require('fs');
var path = require('path');
var url = require('url');
var OSS = require('ali-oss').Wrapper;
var u = require('underscore');
var ConfigFileLoader = require('config-file-loader');
/**
* 读取全局配置
* ~/.aliyun
* @link https://github.com/reyesr/config-file-loader
*/
var aliyunConfig = new ConfigFileLoader.Loader().get('aliyun');
// 默认配置参数
var DEFAULT_OPTIONS = {
ak: '',
sk: '',
bucket: '',
region: '',
retry: 3,
// 多账号支持
account: null,
filter: function (file) {
return true;
}
};
/**
* @constructor
*/
function WebpackAliyunOssPlugin(options) {
this.options = u.extend({}, DEFAULT_OPTIONS, options);
var conf = options.account ? aliyunConfig[options.account] : aliyunConfig;
this.client = new OSS({
region: this.options.region || conf.region,
accessKeyId: this.options.ak || conf.ak,
accessKeySecret: this.options.sk || conf.sk
});
this.client.useBucket(this.options.bucket);
}
WebpackAliyunOssPlugin.prototype.apply = function (compiler) {
var me = this;
compiler.hooks.emit.tapAsync('WebpackAliyunOssPlugin', function (compilation, callback) {
var publicPath = url.parse(compiler.options.output.publicPath);
if (!publicPath.protocol || !publicPath.hostname) {
return callback(new Error('Webpack配置文件中: "output.publicPath"必须设置为域名,例如: https://domain.com/path/'));
}
var files = u.filter(u.keys(compilation.assets), me.options.filter);
if (files.length === 0) {
return callback();
}
function upload(file, times) {
var target = url.resolve(url.format(publicPath), file);
var key = url.parse(target).pathname;
var source = compilation.assets[file].source();
var body = Buffer.isBuffer(source) ? source : new Buffer(source, 'utf8');
return me.client.put(key, body, {
timeout: 30 * 1000
}).then(function () {
console.log('[WebpackAliyunOssPlugin SUCCESS]:', key);
var next = files.shift();
if (next) {
return upload(next, me.options.retry);
}
}, function (e) {
if (times === 0) {
throw new Error('[WebpackAliyunOssPlugin ERROR]: ', e);
}
else {
console.log('[WebpackAliyunOssPlugin retry]:', times, key);
return upload(file, --times);
}
});
}
upload(files.shift(), me.options.retry).then(function () {
console.log('[WebpackAliyunOssPlugin FINISHED]', 'All Completed');
callback();
}).catch(function (e) {
console.log('[WebpackAliyunOssPlugin FAILED]', e);
return callback(e);
});
});
};
module.exports = WebpackAliyunOssPlugin;