-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
92 lines (79 loc) · 2.03 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
const kss = require('kss');
const path = require('path');
function KssPlugin(options) {
if (!options) {
throw 'kss webpack plugin: options is not defined. should be an object with at least "source"';
}
if (!options.source) {
throw 'kss webpack plugin: source is not defined';
}
this.options = options;
}
KssPlugin.prototype.apply = function apply(compiler) {
const kssCompile = () => {
kss(this.options, (error) => {
if (error) throw error;
});
}
const kssRender = (compilation, callback) => {
this.render(compilation, callback);
}
if (!this.options.chunks) {
if (compiler.hooks) {
compiler.hooks.done.tap('KssPlugin', kssCompile);
}
else {
compiler.plugin('done', kssCompile);
}
}
else {
if (compiler.hooks) {
compiler.hooks.emit.tap('KssPlugin', kssRender);
}
else {
compiler.plugin('emit', kssRender);
}
}
};
KssPlugin.prototype.render = function render(compilation, cb) {
const callback = typeof cb === 'function' ? cb : () => {};
new Promise((resolve) => {
const assets = this._buildAssets(compilation);
kss(Object.assign({}, this.options, assets), (error) => {
if (error) throw error;
});
resolve();
})
.then(() => {
callback();
})
.catch(() => {
callback();
})
};
KssPlugin.prototype._buildAssets = function (compilation) {
const assets = {
css: [],
js: []
};
this.options.chunks.forEach((key) => {
const pushAsset = (file) => {
const ext = path.extname(file);
if (ext === '.css') {
assets.css.push(path.join('/', path.join(this.options.assetPath, file)))
} else if (ext === '.js') {
assets.js.push(path.join('/', path.join(this.options.assetPath, file)));
}
}
const asset = compilation.getStats().toJson().assetsByChunkName[key];
if(typeof asset === 'string') {
pushAsset(asset)
} else {
asset.forEach((file) => {
pushAsset(file)
})
}
});
return assets;
};
module.exports = KssPlugin;