1 | "use strict";
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | exports.transpile = transpile;
|
11 |
|
12 | exports.parseToAST = parseToAST;
|
13 |
|
14 |
|
15 | require( "@babel/polyfill" );
|
16 |
|
17 | const
|
18 | Path = require( "path" ),
|
19 | Babel = require( "@babel/core" ),
|
20 | Fatal = require( "./fatal" ),
|
21 | Minify = require( "babel-preset-minify" ),
|
22 | Preset = require( "@babel/preset-env" );
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 | function transpile( sourceCode, sourceName, minify ) {
|
34 | try {
|
35 | const
|
36 | sourceFileName = Path.basename( sourceName ),
|
37 | ast = parseToAST( sourceCode ),
|
38 | transfo = Babel.transformSync( sourceCode, buildOptions( sourceFileName, minify ) ),
|
39 |
|
40 | transpiledCode = transfo.code;
|
41 |
|
42 | return {
|
43 | code: `${transpiledCode}\n//# sourceMappingURL=${sourceFileName}.map`,
|
44 | zip: transpiledCode,
|
45 | map: transfo.map,
|
46 | ast
|
47 | };
|
48 | } catch ( ex ) {
|
49 | console.warn( "================================================================================" );
|
50 | console.warn( sourceCode );
|
51 | console.warn( "================================================================================" );
|
52 | Fatal.fire( `Babel parsing error in ${sourceName}:\n${ex}`, sourceName );
|
53 | }
|
54 | return null;
|
55 | }
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 | function parseToAST( code ) {
|
64 | try {
|
65 | return Babel.parseSync( code );
|
66 | } catch ( ex ) {
|
67 | Fatal.fire( `Babel cannot produce an AST: ${ex}` );
|
68 | return null;
|
69 | }
|
70 | }
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 | function buildOptions( sourceFileName, mustMinify ) {
|
78 | if ( mustMinify ) return {
|
79 | sourceFileName,
|
80 | ast: false,
|
81 | comments: false,
|
82 | sourceMaps: true,
|
83 | presets: [
|
84 | [
|
85 | Minify,
|
86 | {
|
87 | builtIns: false,
|
88 | mangle: false
|
89 | }
|
90 | ],
|
91 | [
|
92 | Preset,
|
93 | { useBuiltIns: "entry" }
|
94 | ]
|
95 | ]
|
96 | };
|
97 |
|
98 | return {
|
99 | sourceFileName,
|
100 | ast: false,
|
101 | comments: true,
|
102 | sourceMaps: true,
|
103 | presets: [
|
104 | [
|
105 | Preset,
|
106 | { useBuiltIns: "entry" }
|
107 | ]
|
108 | ]
|
109 | };
|
110 | } |
\ | No newline at end of file |