/
compile-to-js.es
65 lines (59 loc) · 1.89 KB
/
compile-to-js.es
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
import fs from 'fs-extra'
import path from 'path-extra'
import Promise, { promisify } from 'bluebird'
import { log } from '../lib/utils'
import { transformFile } from '@babel/core'
import BabelConfig from '../babel.config'
import walk from 'walk'
const changeExt = (srcPath, ext) => {
const srcDir = path.dirname(srcPath)
const srcBasename = path.basename(srcPath, path.extname(srcPath))
return path.join(srcDir, srcBasename + ext)
}
const compileToJs = (appDir, dontRemove) => {
log(`Compiling ${appDir}`)
const targetExts = ['.es', '.ts', '.tsx']
const options = {
followLinks: false,
filters: ['node_modules', 'assets', '__tests__', '__mocks__'],
}
const { presets, plugins } = BabelConfig
return new Promise(resolve => {
const tasks = []
walk
.walk(appDir, options)
.on('file', (root, fileStats, next) => {
const extname = path.extname(fileStats.name).toLowerCase()
if (targetExts.includes(extname)) {
tasks.push(async () => {
const srcPath = path.join(root, fileStats.name)
const tgtPath = changeExt(srcPath, '.js')
// const src = await fs.readFile(srcPath, 'utf-8')
let tgt
try {
const result = await promisify(transformFile)(srcPath, {
presets,
plugins,
})
tgt = result.code
} catch (e) {
log(`Compiling ${srcPath} failed: ${e}`)
log(e.stack)
return
}
await fs.writeFile(tgtPath, tgt)
if (!dontRemove) {
await fs.remove(srcPath)
}
log(`Compiled ${tgtPath}`)
})
}
next()
})
.on('end', async () => {
log(`Files to compile: ${tasks.length} files`)
resolve(await Promise.all(tasks.map(f => f())))
})
})
}
export default compileToJs