-
Notifications
You must be signed in to change notification settings - Fork 599
/
index.js
102 lines (90 loc) 路 2.65 KB
/
index.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
import type {BabelCoreOptions} from '@babel/core';
import type {FBSourceFunctionMap} from 'metro-source-map';
const {parseSync, transformFromAstSync} = require('@babel/core');
const HermesParser = require('hermes-parser');
const {generateFunctionMap} = require('metro-source-map');
const nullthrows = require('nullthrows');
export type CustomTransformOptions = {
[string]: mixed,
__proto__: null,
...
};
export type TransformProfile = 'default' | 'hermes-stable' | 'hermes-canary';
type BabelTransformerOptions = $ReadOnly<{
customTransformOptions?: CustomTransformOptions,
dev: boolean,
enableBabelRCLookup?: boolean,
enableBabelRuntime: boolean | string,
extendsBabelConfigPath?: string,
experimentalImportSupport?: boolean,
hermesParser?: boolean,
hot: boolean,
inlineRequires: boolean,
nonInlinedRequires?: $ReadOnlyArray<string>,
minify: boolean,
unstable_disableES6Transforms?: boolean,
platform: ?string,
projectRoot: string,
publicPath: string,
unstable_transformProfile?: TransformProfile,
globalPrefix: string,
...
}>;
export type BabelTransformerArgs = $ReadOnly<{|
filename: string,
options: BabelTransformerOptions,
plugins?: $PropertyType<BabelCoreOptions, 'plugins'>,
src: string,
|}>;
export type BabelTransformer = {|
transform: BabelTransformerArgs => {
ast: BabelNodeFile,
functionMap: ?FBSourceFunctionMap,
...
},
getCacheKey?: () => string,
|};
function transform({filename, options, plugins, src}: BabelTransformerArgs) {
const OLD_BABEL_ENV = process.env.BABEL_ENV;
process.env.BABEL_ENV = options.dev
? 'development'
: process.env.BABEL_ENV || 'production';
try {
const babelConfig = {
caller: {name: 'metro', bundler: 'metro', platform: options.platform},
ast: true,
babelrc: options.enableBabelRCLookup,
code: false,
highlightCode: true,
filename,
plugins,
sourceType: 'module',
};
const sourceAst = options.hermesParser
? HermesParser.parse(src, {
babel: true,
sourceType: babelConfig.sourceType,
})
: parseSync(src, babelConfig);
const {ast} = transformFromAstSync(sourceAst, src, babelConfig);
const functionMap = generateFunctionMap(sourceAst, {filename});
return {ast: nullthrows(ast), functionMap};
} finally {
if (OLD_BABEL_ENV) {
process.env.BABEL_ENV = OLD_BABEL_ENV;
}
}
}
module.exports = ({
transform,
}: BabelTransformer);