-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
51 lines (43 loc) · 1.49 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
'use strict';
var util = require('gulp-util');
var PluginError = util.PluginError;
var through = require('through2');
var extend = require('extend');
var PLUGIN_NAME = 'gulp-px2rpx';
var defaultConfig = {
unit: 'rpx', // 单位
replaceUnit: 'px', // 被替换的
screenWidth: 750, // 设计稿屏幕
wxappScreenWidth: 750, // 微信小程序屏幕
remPrecision: 6 // 小数精度, 默认6
};
function gulpPx2Rpx (options) {
options = extend({}, defaultConfig, options);
var reg = new RegExp('([\\d.]*\\d)' + options.replaceUnit, 'g');
var ratio = options.wxappScreenWidth / options.screenWidth;
var remPrecision = options.remPrecision;
function getValue(val) {
val = parseFloat(val.toFixed(remPrecision)); // control decimal precision of the calculated value
return val == 0 ? val : val + options.unit;
}
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit('error', new PluginError(PLUGIN_NAME, 'Streaming not supported'));
return cb();
}
try {
file.contents = new Buffer(file.contents.toString().replace(reg, function (m, p1) {
return getValue(p1 * ratio);
}));
} catch (err) {
this.emit('error', new PluginError(PLUGIN_NAME, err));
}
this.push(file);
return cb();
});
}
module.exports = gulpPx2Rpx;