UNPKG

3.17 kBJavaScriptView Raw
1"use strict";
2
3/**
4 * Transpile code into Javascript equivalent that can be read on currently supported browsers.
5 * @param {string} sourceCode - Code in cutting edge Javascript.
6 * @returns {object} The transpiled code and its source map.
7 * __code__: code compatible with currently supported browsers.
8 * __map__: source map.
9 */
10exports.transpile = transpile;
11
12exports.parseToAST = parseToAST;
13
14
15require( "@babel/polyfill" );
16
17const
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 * Transpile code into Javascript equivalent that can be read on currently supported browsers.
26 * @param {string} sourceCode - Code in cutting edge Javascript.
27 * @param {string} sourceName - Name of the file.
28 * @param {boolean} minify - Default `false`.
29 * @returns {object} The transpiled code and its source map.
30 * __code__: code compatible with currently supported browsers.
31 * __map__: source map.
32 */
33function 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 // transfo = Babel.transformFromAstSync( ast, OPTIONS ),
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 * @param {string} code - Javascript source code.
60 * @returns {object}
61 * AST.
62 */
63function 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 * @param {string} sourceFileName - Name of the file.
74 * @param {boolean} mustMinify - Default `false`.
75 * @returns {object} Options to use in Babel transformation.
76 */
77function 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