1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | const webpack = require('webpack');
|
23 | const memoryFs = new (require('memory-fs'))();
|
24 | const { jsLogger } = require('./loggers');
|
25 | const { PrepCache } = require('./utils');
|
26 | const { jsCssErr } = require('./errors');
|
27 |
|
28 |
|
29 |
|
30 | module.exports = function({srcDir, loggerFn, options}) {
|
31 |
|
32 | const { isDev, isBuild } = options;
|
33 |
|
34 | |
35 |
|
36 |
|
37 |
|
38 |
|
39 | const configureWebpack = require('./util/config-webpack')(srcDir, isDev, options);
|
40 | const compilerCache = new PrepCache((srcFile) => {
|
41 |
|
42 | const compiler = webpack(configureWebpack(srcFile));
|
43 | compiler.outputFileSystem = memoryFs;
|
44 | return compiler;
|
45 | });
|
46 |
|
47 | return function(srcFile) {
|
48 |
|
49 | const compiler = compilerCache.get(srcFile);
|
50 | return new Promise((resolve, reject) => {
|
51 | compiler.run((err, stats) => {
|
52 | if (err) reject({err});
|
53 | else if (stats.hasErrors()||stats.hasWarnings()) reject({stats});
|
54 | else resolve(memoryFs.readFileSync(srcFile));
|
55 | });
|
56 | })
|
57 |
|
58 |
|
59 | .then((data) => data)
|
60 | .catch(({err, stats}) => {
|
61 |
|
62 | let message;
|
63 | if (err) {
|
64 | message = err.stack || err;
|
65 | if (err.details) { message = err.details; }
|
66 | if (isBuild) throw Error(message);
|
67 | return jsCssErr(message);
|
68 | }
|
69 |
|
70 | const info = stats.toJson({});
|
71 |
|
72 | if (stats.hasErrors()) { message = info.errors; }
|
73 | if (stats.hasWarnings()) { message = info.warnings; }
|
74 | if (isBuild) throw Error(message);
|
75 | loggerFn.error(message);
|
76 | return jsCssErr(message);
|
77 | });
|
78 | };
|
79 | };
|