-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
49 lines (45 loc) · 1.29 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
/* eslint-disable es5/no-es6-static-methods */
/* eslint-disable es5/no-block-scoping */
let postcss = require('postcss')
let OSS = require('ali-oss')
let path = require('path')
let md5File = require('md5-file')
let qiniuUpload = require('./qiniu')
function aliossUpload (remotePath, localFile, client) {
return new Promise((resolve, reject) => {
try {
client
.put(remotePath, localFile)
.then(res => {
let url = res.url
resolve(url)
})
.catch(err => {
reject(err)
})
} catch (e) {
reject(e)
}
})
}
module.exports = postcss.plugin('postcss-assets-urls', opts => {
opts = opts || {}
// Work with options here
return function (root) {
let uploadList = []
let client = opts.oss && new OSS(opts.oss)
root.walkDecls(/background/, decl => {
decl.value = decl.value.replace(/\/assets\/\S*.(png|svg|jpg)/, match => {
let file = path.join(process.cwd(), match)
let hash = md5File.sync(file, match)
let upload = aliossUpload(hash, file, client)
if (opts.qiniu) {
upload = qiniuUpload(opts.qiniu, file)
}
client && uploadList.push(upload)
return [opts.baseUrl || '', hash].join('/')
})
})
return Promise.all(uploadList)
}
})