forked from tivac/modular-css
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.js
110 lines (88 loc) · 3.04 KB
/
plugin.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
102
103
104
105
106
107
108
109
110
"use strict";
var sources = require("webpack-sources"),
Processor = require("modular-css-core"),
ismap = require("lodash.ismap");
// Return a list of changed/removed files based on timestamp objects
function getChangedFiles(prev, curr) {
return Object.keys(curr)
.filter((file) =>
!prev[file] || prev[file] < curr[file]
)
.concat(
Object.keys(prev).filter((file) => !curr[file])
);
}
function ModularCSS(args) {
var options = Object.assign(
Object.create(null),
args
);
if(options.cjs) {
options.namedExports = false;
}
this.prev = {};
this.processor = new Processor(options);
this.options = options;
}
ModularCSS.prototype.apply = function(compiler) {
var watching = false;
// File invalidated by webpack watcher
compiler.plugin("invalid", (file) => {
this.processor.remove(file);
});
compiler.plugin("watch-run", (c, done) => {
watching = true;
done();
});
// Runs before compilation begins
compiler.plugin("this-compilation", (compilation) => {
var files;
// Make processor instance available to the loader
compilation.options.processor = this.processor;
// This code is only useful when calling .run() multiple times
// watching handles its own invalidations
if(!watching) {
let current;
if(ismap(compilation.fileTimestamps)) {
current = {};
compilation.fileTimestamps.forEach((value, key) => (current[key] = value));
}
files = getChangedFiles(this.prev, current || compilation.fileTimestamps);
// Remove changed/removed files from processor instance
this.processor.remove(files);
this.prev = compilation.fileTimestamps;
}
});
compiler.plugin("emit", (compilation, done) =>
this.processor.output({
to : this.options.css || false,
})
.then((data) => {
if(this.options.css) {
compilation.assets[this.options.css] = data.map ?
new sources.SourceMapSource(
data.css,
this.options.css,
data.map
) :
new sources.RawSource(
data.css
);
// Write out external source map if it exists
if(data.map) {
compilation.assets[`${this.options.css}.map`] = new sources.RawSource(
data.map.toString()
);
}
}
if(this.options.json) {
compilation.assets[this.options.json] = new sources.RawSource(
JSON.stringify(data.compositions, null, 4)
);
}
return done();
})
.catch(done)
);
};
module.exports = ModularCSS;