-
Notifications
You must be signed in to change notification settings - Fork 33
/
base.js
82 lines (73 loc) · 2.39 KB
/
base.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
/**
* @file base file compiler
* @author zhangwentao <winty2013@gmail.com>
*/
/* eslint-disable fecs-min-vars-per-destructure */
/* eslint-disable fecs-no-require */
const buildInProcessors = require('./processor');
async function process(source, processors) {
for (const processor of processors) {
const {name, options = {}, process} = processor;
if (typeof process === 'function') {
source = await process(source, options);
}
else if (buildInProcessors[name]) {
source = await buildInProcessors[name](source, options);
}
else {
throw new Error('[processor not found]', processor);
}
}
return source;
}
function getExtProcessors(processors, lang) {
let ret = [];
Object.keys(processors).forEach(name => {
let val = processors[name];
if (Array.isArray(val)) {
val = {
extnames: val
}
}
let {extnames, options = {}, process} = val;
if (Array.isArray(extnames) && extnames.indexOf(lang) > -1) {
ret.push({
name,
options,
process
});
}
});
return ret;
}
function getFileCompiler(compile, config) {
const {preprocessors = {}, postprocessors = {}} = config;
return async function fileCompiler(file, options) {
const fileOptions = file.$options;
const lang = file.lang || file.type;
let source = (file.contents && file.contents.toString()) || '';
// preprocessors
source = await process(source, getExtProcessors(preprocessors, lang));
// compile
options.path = file.path;
options.file = file;
const result = await compile(source, options, fileOptions);
// postprocessors
let {code, ...rest} = result;
code = await process(code, getExtProcessors(postprocessors, lang));
// overwrite file contents
file.contents = new Buffer(code || '');
return rest;
};
}
function getFileCompilers(compilers = {}, options) {
const buildConfig = options._config || {};
let ret = {};
Object.keys(compilers).forEach(key => {
const compiler = compilers[key];
ret[key] = getFileCompiler(compiler, buildConfig);
});
return ret;
}
exports.getFileCompiler = getFileCompiler;
exports.getFileCompilers = getFileCompilers;