-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.js
96 lines (83 loc) · 2.59 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
93
94
95
96
const prettier = require("prettier");
const fs = require("fs");
const path = require("path");
const DEFAULT_EXTENSIONS = prettier.getSupportInfo
? prettier
.getSupportInfo()
.languages.map(l => l.extensions)
.reduce((accumulator, currentValue) => accumulator.concat(currentValue))
: [
".css",
".graphql",
".js",
".json",
".jsx",
".less",
".sass",
".scss",
".ts",
".tsx",
".vue",
".yaml",
];
const DEFAULT_ENCODING = "utf-8";
const DEFAULT_CONFIG_FILE = `${process.cwd()}/.prettierrc`;
module.exports = class PrettierPlugin {
constructor(options) {
options = options || {};
// Encoding to use when reading / writing files
this.encoding = options.encoding || DEFAULT_ENCODING;
delete options.encoding;
// Only process these files
this.extensions = options.extensions || DEFAULT_EXTENSIONS;
delete options.extensions;
// Utilize this config file for options
this.configFile = options.configFile || DEFAULT_CONFIG_FILE;
delete options.configFile;
// Resolve the config options from file to an object
const configOptions = prettier.resolveConfig.sync(this.configFile) || {};
// Override Prettier options from config if any are specified
this.prettierOptions = Object.assign(configOptions, options);
}
apply(compiler) {
compiler.hooks.emit.tapAsync('Prettier', (compilation, callback) => {
const promises = [];
compilation.fileDependencies.forEach(filepath => {
if (this.extensions.indexOf(path.extname(filepath)) === -1) {
return;
}
if (/node_modules/.exec(filepath)) {
return;
}
promises.push(new Promise((resolve, reject) => {
fs.readFile(filepath, this.encoding, (err, source) => {
if (err) {
return reject(err);
}
try{
const prettierSource = prettier.format(source, Object.assign({}, this.prettierOptions, { filepath }));
if (prettierSource !== source) {
fs.writeFile(filepath, prettierSource, this.encoding, err => {
if (err) {
return reject(err);
}
resolve();
});
} else {
resolve();
}
}
catch(err){
return reject(err);
}
});
}));
});
Promise.all(promises).then(() => {
callback();
}).catch(err => {
callback(err);
});
});
}
};