/
run-babel.js
60 lines (46 loc) · 1.55 KB
/
run-babel.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
const { transform } = require('@babel/core');
const fse = require('fs-extra');
const path = require('path');
let getConfig = ({ modules = true, optimize = true, test = false } = {}) => {
delete require.cache[require.resolve('../.babelrc.js')];
const devEnv = test ? 'test' : 'development';
process.env.NODE_ENV = optimize ? 'production' : devEnv;
process.env.BABEL_ENV = modules ? '' : 'esm';
return require('../.babelrc.js');
};
async function buildFile(filename, destination, babelOptions = {}) {
if (!path.extname(filename) === '.js') return;
const content = await fse.readFile(filename, { encoding: 'utf8' });
const result = transform(content, { ...babelOptions, filename });
const output = path.join(destination, path.basename(filename));
await fse.outputFile(output, result.code);
}
async function _build(
folderPath,
destination,
babelOptions = {},
firstFolder = true
) {
let stats = fse.statSync(folderPath);
if (stats.isFile()) {
await buildFile(folderPath, destination, babelOptions);
} else if (stats.isDirectory()) {
let outputPath = firstFolder
? destination
: path.join(destination, path.basename(folderPath));
let files = (await fse.readdir(folderPath)).map(file =>
path.join(folderPath, file)
);
await Promise.all(
files.map(f => _build(f, outputPath, babelOptions, false))
);
}
}
module.exports = function buildBabel(
folderPath,
destination,
babelConfig = {}
) {
return _build(folderPath, destination, getConfig(babelConfig));
};
module.exports.getConfig = getConfig;