forked from elm-community/elm-webpack-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
76 lines (63 loc) · 2.04 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
'use strict';
var loaderUtils = require('loader-utils');
var elmCompiler = require('node-elm-compiler');
var path = path || require('path');
var cachedDependencies;
var defaultOptions = {
cache: false,
yes: true
};
var getInput = function() {
return this.resourcePath;
};
var getOptions = function() {
var globalOptions = this.options.elm || {};
var loaderOptions = loaderUtils.parseQuery(this.query);
return Object.assign({
emitWarning: this.emitWarning
}, defaultOptions, globalOptions, loaderOptions);
};
var walkSync = function(dir, filelist) {
var fs = fs || require('fs'),
files = fs.readdirSync(dir);
filelist = filelist || [];
files.forEach(function(file) {
if (fs.statSync(path.join(dir, file)).isDirectory()) {
filelist = walkSync(path.join(dir, file), filelist);
}
else {
filelist.push(path.join(dir, file));
}
});
return filelist;
};
module.exports = function() {
this.cacheable && this.cacheable();
var callback = this.async();
if (!callback) {
throw 'elm-webpack-loader currently only supports async mode.';
}
var input = getInput.call(this);
var options = getOptions.call(this);
var dependencies = Promise.resolve()
.then(() => {
var baseDir = path.dirname(input);
var elmFiles = walkSync(baseDir, []);
elmFiles.forEach(dependency => this.addDependency(dependency));
})
.then(function(v) { return { kind: 'success', result: v }; })
.catch(function(v) { return { kind: 'error', error: v }; });
var compilation = elmCompiler.compileToString(input, options)
.then(function(v) { return { kind: 'success', result: v }; })
.catch(function(v) { return { kind: 'error', error: v }; });
Promise.all([dependencies, compilation])
.then(function(results) {
var output = results[1]; // compilation output
if (output.kind == 'success') {
callback(null, output.result);
} else {
output.error.message = 'Compiler process exited with error ' + output.error.message;
callback(output.error);
}
});
}