/
index.js
90 lines (79 loc) 路 2.16 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
/**
* Copyright (c) Facebook, Inc. and its 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';
const {parseSync, transformFromAstSync} = require('@babel/core');
const {generateFunctionMap} = require('metro-source-map');
import type {Ast, Plugins} from '@babel/core';
import type {FBSourceFunctionMap} from 'metro-source-map';
export type CustomTransformOptions = {
[string]: mixed,
__proto__: null,
...
};
type BabelTransformerOptions = $ReadOnly<{
customTransformOptions?: CustomTransformOptions,
dev: boolean,
disableFlowStripTypesTransform?: boolean,
enableBabelRCLookup?: boolean,
enableBabelRuntime: boolean,
extendsBabelConfigPath?: string,
experimentalImportSupport?: boolean,
hot: boolean,
inlineRequires: boolean,
minify: boolean,
unstable_disableES6Transforms?: boolean,
platform: ?string,
projectRoot: string,
publicPath: string,
...
}>;
export type BabelTransformerArgs = $ReadOnly<{|
filename: string,
options: BabelTransformerOptions,
plugins?: Plugins,
src: string,
|}>;
export type BabelTransformer = {|
transform: BabelTransformerArgs => {
ast: Ast,
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', platform: options.platform},
ast: true,
babelrc: options.enableBabelRCLookup,
code: false,
highlightCode: true,
filename,
plugins,
sourceType: 'module',
};
const sourceAst = parseSync(src, babelConfig);
const {ast} = transformFromAstSync(sourceAst, src, babelConfig);
const functionMap = generateFunctionMap(sourceAst, {filename});
return {ast, functionMap};
} finally {
if (OLD_BABEL_ENV) {
process.env.BABEL_ENV = OLD_BABEL_ENV;
}
}
}
module.exports = ({
transform,
}: BabelTransformer);