-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
102 lines (97 loc) · 2.75 KB
/
index.js
File metadata and controls
102 lines (97 loc) · 2.75 KB
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
97
98
99
100
101
102
'use strict';
const path = require('path');
const babelCore = require('@babel/core');
const _ = require('lodash');
function genRule(rule) {
if (rule.indexOf('/') === 0) {
rule = '^' + rule;
}
return new RegExp(rule.replace(/\./g, '\\.').replace(/\*/g, '.*'));
}
function importPlugin(nameString) {
let plugin = null;
if (/^\//.test(nameString)) {
// absolute import
const pluginPath = nameString.slice(1);
plugin = require(__dirname, '../..', pluginPath);
} else if (/^(\.\/|\.\.\/)/.test(nameString)) {
// relative import
plugin = require(__dirname, '../..', nameString);
} else if (/^(babel-plugin-|@\w+\/[\w-]+)/.test(nameString)) {
// full-name or with scope
plugin = require(nameString);
} else {
// shorthand
plugin = require('babel-plugin-' + nameString)
}
// 部分插件导出 { default: [Function] } 形式
return plugin.default ? plugin.default : plugin;
}
class BabelProcessor {
constructor(cube, config) {
this.cube = cube;
this.config = this.prepareConfig(config);
let ignore = this.config.ignore;
let ignoreRules = [];
ignore && ignore.forEach((rule) => {
ignoreRules.push(genRule(rule));
});
this.ignoreRules = ignoreRules;
}
process(data, callback) {
let code = data.code;
let res;
let ignore = this.ignoreRules;
for (let i = 0, len = ignore.length; i < len; i++) {
if (ignore[i].test(data.queryPath)) {
return callback(null, data);
}
}
if (data.noAstParse) {
return callback(null, data);
}
let config = {
ast: true,
code: true,
filename: data.realPath,
sourceRoot: this.cube.config.root,
comments: false,
};
babelCore.transform(code, _.merge(config, this.config), (err, res) => {
if (err) {
return callback(err);
}
data.code = res.code;
callback(null, data);
});
}
prepareConfig(config) {
try {
config.presets && config.presets.forEach((v, i, a) => {
if (Array.isArray(v) && typeof v[0] === 'string') {
if (!v[0].startsWith('@babel/')) {
v[0] = '@babel/preset-' + v[0];
}
} else if (typeof v === 'string') {
if (!v.startsWith('@babel/')) {
a[i] = '@babel/preset-' + v;
}
}
});
config.plugins && config.plugins.forEach((v, i, a) => {
if (Array.isArray(v) && typeof v[0] === 'string') {
v[0] = importPlugin(v[0]);
} else if (typeof v === 'string') {
a[i] = importPlugin(v);
}
});
} catch (e) {
e.message = 'cube-babel config error:' + e.message;
throw e;
}
return config;
}
}
BabelProcessor.ext = '.js';
BabelProcessor.type = 'script';
module.exports = BabelProcessor;