This repository has been archived by the owner on Feb 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathdir-list-webpack-plugin.js
86 lines (79 loc) · 2.49 KB
/
dir-list-webpack-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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const fs = require("fs");
const path = require("path");
function statPromise(path) {
return new Promise((resolve, reject) => {
fs.stat(path, (err, stat) => {
err ? reject(err) : resolve(stat);
});
});
}
module.exports = class DirListWebpackPlugin {
constructor(options) {
this.options = {
directory: undefined,
filename: undefined,
filter: undefined,
compareFunction: undefined,
...options,
};
}
apply(compiler) {
compiler.plugin("emit", (compilation, callback) => {
if (!this.options.directory) {
compilation.errors.push("DirListWebpackPlugin directory undefined");
callback();
return;
}
if (!this.options.filename) {
compilation.errors.push("DirListWebpackPlugin filename undefined");
callback();
return;
}
const directory = path.resolve(compiler.context, this.options.directory);
fs.readdir(directory, (err, files) => {
if (err) {
compilation.errors.push(`DirListWebpackPlugin couldn't read ` +
`directory ${this.options.directory}`);
callback();
return;
}
let filesPromise;
if (this.options.filter) {
filesPromise = Promise.all(files.map((f) => {
const filename = path.join(directory, f);
return statPromise(filename).then(
(stats) => this.options.filter(f, stats),
() => {
compilation.errors.push(`DirListWebpackPlugin couldn't stat ` +
`directory ${filename}`);
callback();
}
);
})).then((filtered) => {
return files.filter((_, i) => filtered[i]);
});
} else {
filesPromise = Promise.resolve(files);
}
filesPromise.then((files) => {
if (this.options.compareFunction) {
files.sort(this.options.compareFunction);
}
const output = JSON.stringify(files);
compilation.assets[this.options.filename] = {
source() {
return output;
},
size() {
return output.length;
},
};
callback();
});
});
});
}
};