-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
104 lines (86 loc) · 2.45 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
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
103
/**
* @file fis3 babel6 parser 模块
* @author sparklewhy@gmail.com
*/
'use strict';
var path = require('path');
var fs = require('fs');
var qrequire = require('qrequire');
var json5 = require('json5');
var speeded = false;
/**
* 读取 babel 配置
*
* @return {?Object}
*/
function readBabelConfig() {
var _ = fis.util;
var currDir = process.cwd();
var babelRcFile = path.resolve(currDir, '.babelrc');
if (_.isFile(babelRcFile)) {
return json5.parse(fs.readFileSync(babelRcFile, 'utf-8'));
}
var pkgMetaFile = path.resolve(currDir, 'package.json');
if (_.isFile(pkgMetaFile)) {
return require(pkgMetaFile).babel;
}
}
/**
* 使用 babel6 编译代码文件
*
* @param {string} content 代码内容
* @param {Object} file 文件对象
* @param {Object} conf 定制配置
* @return {string}
*/
function compile(content, file, conf) {
if (file.disableBabel) {
return content;
}
// init options
var _ = fis.util;
var options = _.assign({
filename: file.subpath.replace(/^\/+/, '') // remove start slash
}, readBabelConfig() || {}, conf);
// hook require when enable speed
var useSpeed = options.speed;
delete options.speed;
if (useSpeed && !speeded) {
qrequire.hook();
speeded = true;
}
else {
useSpeed = false;
}
// transform code
var result = exports.parser.transform(content, options);
// extract used babel helper api
if (result.metadata
&& result.metadata.usedHelpers
) {
// cache the used babel helper information
var usedHelpers = result.metadata.usedHelpers;
file.extras.babelHelpers = usedHelpers;
}
useSpeed || qrequire.unhook();
// init source map
var sourceMaps = options.sourceMaps;
if (sourceMaps && sourceMaps !== 'inline' && result.map) {
var sourceMapPath = file.realpath + '.map';
var sourceMapFile = fis.file.wrap(sourceMapPath);
sourceMapFile.setContent(JSON.stringify(result.map, null, 2));
file.derived.push(sourceMapFile);
var sourceMapUrl = sourceMapFile.getUrl(
fis.compile.settings.hash, fis.compile.settings.domain
);
result.code += '\n//# sourceMappingURL=' + sourceMapUrl + '\n';
}
return result.code;
}
module.exports = exports = compile;
/**
* 使用的 parser,从外部传入,不直接集成到该插件里
*
* @type {Object}
*/
exports.parser = null;