1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | 'use strict'
|
13 |
|
14 | const aglob = require('aglob')
|
15 | const convertSourceMap = require('convert-source-map')
|
16 | const writeout = require('writeout')
|
17 | const path = require('path')
|
18 | const filedel = require('filedel')
|
19 | const { statAsync } = require('asfs')
|
20 | const { isProduction } = require('asenv')
|
21 | const { transformFile } = require('@babel/core')
|
22 | const { DEFAULT_PRESET, DEFAULT_EXT } = require('./constants')
|
23 |
|
24 | const { replaceExt } = require('./helpers/file_helper')
|
25 | const relative = (filename) => path.relative(process.cwd(), filename)
|
26 | const mtime = (filename) => statAsync(filename).catch(() => null).then((stat) => stat && stat.mtime)
|
27 |
|
28 |
|
29 | async function ababel(pattern, options = {}) {
|
30 | let {
|
31 | cwd = process.cwd(),
|
32 | out = process.cwd(),
|
33 | force = false,
|
34 | presets = DEFAULT_PRESET.split(','),
|
35 | sourceMaps = !isProduction(),
|
36 | minified = false,
|
37 | ignore = [],
|
38 | reflects = [],
|
39 | plugins = [],
|
40 | sourceRoot,
|
41 | ext = DEFAULT_EXT.split(','),
|
42 | } = options
|
43 |
|
44 | try {
|
45 | const filenames = await aglob(pattern, { cwd, ignore })
|
46 | reflects = await aglob(reflects)
|
47 | for (const filename of filenames) {
|
48 | const src = relative(path.resolve(cwd, filename))
|
49 | const dest = relative(path.resolve(out, ext.reduce((filename, ext) => replaceExt(filename, ext, '.js'), filename)))
|
50 | if (!isProduction() && !force) {
|
51 | const srcMtime = await mtime(src)
|
52 | const destMtime = await mtime(dest)
|
53 | const skip = srcMtime && destMtime && (srcMtime <= destMtime)
|
54 | if (skip) {
|
55 | continue
|
56 | }
|
57 | }
|
58 | const { code, map, ast } = await new Promise((resolve, reject) => {
|
59 | const options = {
|
60 | presets,
|
61 | minified,
|
62 | sourceMaps,
|
63 | compact: false,
|
64 | babelrc: false,
|
65 | filename: path.resolve(src),
|
66 | filenameRelative: path.relative(cwd, path.resolve(src)),
|
67 | sourceRoot: sourceRoot || path.relative(out, cwd),
|
68 | plugins: ['@babel/plugin-transform-runtime', ...plugins],
|
69 | }
|
70 | transformFile(src, options, (err, result) => err ? reject(err) : resolve(result))
|
71 | })
|
72 | try {
|
73 | if (dest !== src) {
|
74 | await filedel(dest)
|
75 | }
|
76 | } catch (err) {
|
77 |
|
78 | }
|
79 | const { skipped } = await writeout(dest, `${code}\n${convertSourceMap.fromObject(map).toComment()}`, {
|
80 | mkdirp: true,
|
81 | skipIfIdentical: true
|
82 | })
|
83 | if (!skipped) {
|
84 | console.log(`File generated: ${relative(dest)}`)
|
85 | }
|
86 |
|
87 | }
|
88 | } catch (err) {
|
89 | throw err
|
90 | }
|
91 | }
|
92 |
|
93 | module.exports = ababel
|