index.js
2.13 KB
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
var LastCallWebpackPlugin = require('last-call-webpack-plugin');
function OptimizeCssAssetsPlugin(options) {
this.options = options || {};
if (this.options.assetNameRegExp === undefined) {
this.options.assetNameRegExp = /\.css$/g;
}
if (this.options.cssProcessor === undefined) {
this.options.cssProcessor = require('cssnano');
}
if (this.options.cssProcessorOptions === undefined) {
this.options.cssProcessorOptions = {};
}
if (this.options.canPrint === undefined) {
this.options.canPrint = true;
}
var self = this;
this.lastCallInstance = new LastCallWebpackPlugin({
assetProcessors: [
{
phase: LastCallWebpackPlugin.PHASE.OPTIMIZE_CHUNK_ASSETS,
regExp: this.options.assetNameRegExp,
processor: function (assetName, asset, assets) {
return self.processCss(assetName, asset, assets);
},
}
],
canPrint: this.options.canPrint
});
};
OptimizeCssAssetsPlugin.prototype.processCss = function(assetName, asset, assets) {
var css = asset.source();
var processOptions = Object.assign(
{ from: assetName, to: assetName },
this.options.cssProcessorOptions || {}
);
if (processOptions.map && !processOptions.map.prev) {
try {
var mapJson = assets.getAsset(assetName + '.map');
if (mapJson) {
var map = JSON.parse(mapJson);
if (
map &&
(
(map.sources && map.sources.length > 0) ||
(map.mappings && map.mappings.length > 0)
)
) {
processOptions.map = Object.assign({ prev: mapJson }, processOptions.map);
}
}
} catch (err) {
console.warn('OptimizeCssAssetsPlugin.processCss() Error getting previous source map', err);
}
}
return this.options
.cssProcessor.process(css, processOptions)
.then(r => {
if (processOptions.map && r.map && r.map.toString) {
assets.setAsset(assetName + '.map', r.map.toString());
}
return r.css;
});
};
OptimizeCssAssetsPlugin.prototype.apply = function(compiler) {
return this.lastCallInstance.apply(compiler);
};
module.exports = OptimizeCssAssetsPlugin;