UNPKG

2.56 kBJavaScriptView Raw
1// _ _
2// | | (_)
3// _ __ ___ _ __ __| | ___ _ __ ______ _ ___
4// | '__/ _ \ '_ \ / _` |/ _ \ '__|______| / __|
5// | | | __/ | | | (_| | __/ | | \__ \
6// |_| \___|_| |_|\__,_|\___|_| | |___/
7// _/ |
8// |__/
9
10// node
11
12// npm
13
14/*
15 createWebpackConfig(srcFile, reqFile, options)
16 createEslintConfig()
17 shimPug(locals)
18 shimSCSS(locals)
19
20*/
21
22const webpack = require('webpack');
23const memoryFs = new (require('memory-fs'))();
24const { jsLogger } = require('./loggers');
25const { PrepCache } = require('./utils');
26const { jsCssErr } = require('./errors');
27
28
29// export
30module.exports = function({srcDir, loggerFn, options}) {
31
32 const { isDev, isBuild } = options;
33
34 /* WEBPACK CONFIG and COMPILER-CACHE
35
36 */
37 // TODO: add linting
38 // const doLinting = options.linting && options.eslintConfig;
39 const configureWebpack = require('./util/config-webpack')(srcDir, isDev, options);
40 const compilerCache = new PrepCache((srcFile) => {
41 // NB: consider this alternate way to create compiler https://webpack.js.org/api/compiler/
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}); // only for webpack errors e.g. misconfig
53 else if (stats.hasErrors()||stats.hasWarnings()) reject({stats});
54 else resolve(memoryFs.readFileSync(srcFile)); // consider using readFile(srcFile, (err, data) => {/**/}) here
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 // the options for this are documented here https://webpack.js.org/configuration/stats/
70 const info = stats.toJson({/* options */});
71 // const info = stats.toString({/* options */}); // this includes "color": true|false for console colors
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};