@react-native/metro-babel-transformer 0.73.7 → 0.73.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,21 +1,19 @@
1
1
  {
2
2
  "name": "@react-native/metro-babel-transformer",
3
- "version": "0.73.7",
3
+ "version": "0.73.9",
4
4
  "description": "Babel transformer for React Native applications.",
5
- "main": "src/index.js",
5
+ "exports": {
6
+ ".": "./src/index.js",
7
+ "./package.json": "./package.json"
8
+ },
9
+ "files": [
10
+ "src"
11
+ ],
6
12
  "repository": {
7
13
  "type": "git",
8
14
  "url": "git@github.com:facebook/react-native.git",
9
15
  "directory": "packages/react-native-babel-transformer"
10
16
  },
11
- "scripts": {
12
- "prepare-release": "test -d lib && mv src src.real && mv lib src",
13
- "cleanup-release": "test ! -e lib && mv src lib && mv src.real src && rimraf lib",
14
- "build-clean": "rimraf build && rimraf src.real",
15
- "build": " node scripts/build.js --verbose",
16
- "prepare": "yarn run build-clean && yarn run build && yarn run prepare-release",
17
- "postpublish": "yarn run cleanup-release"
18
- },
19
17
  "keywords": [
20
18
  "transformer",
21
19
  "react-native",
@@ -29,24 +27,6 @@
29
27
  "hermes-parser": "0.14.0",
30
28
  "nullthrows": "^1.1.1"
31
29
  },
32
- "devDependencies": {
33
- "@babel/plugin-proposal-class-properties": "^7.18.0",
34
- "@babel/plugin-proposal-nullish-coalescing-operator": "^7.18.0",
35
- "@babel/plugin-proposal-object-rest-spread": "^7.20.0",
36
- "@babel/plugin-proposal-optional-chaining": "^7.20.0",
37
- "@babel/plugin-syntax-dynamic-import": "^7.8.0",
38
- "@babel/plugin-transform-async-to-generator": "^7.20.0",
39
- "@babel/plugin-transform-destructuring": "^7.20.0",
40
- "@babel/plugin-transform-flow-strip-types": "^7.20.0",
41
- "@babel/preset-env": "^7.20.0",
42
- "chalk": "^4.0.0",
43
- "glob": "^7.1.1",
44
- "invariant": "^2.2.4",
45
- "micromatch": "^4.0.4",
46
- "mkdirp": "^0.5.1",
47
- "prettier": "2.8.8",
48
- "rimraf": "^3.0.2"
49
- },
50
30
  "peerDependencies": {
51
31
  "@babel/core": "*"
52
32
  },
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow strict-local
8
+ * @format
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ const {transform} = require('../index.js');
14
+ const path = require('path');
15
+
16
+ const PROJECT_ROOT = path.sep === '/' ? '/my/project' : 'C:\\my\\project';
17
+
18
+ it('exposes the correct absolute path to a source file to plugins', () => {
19
+ let visitorFilename;
20
+ let pluginCwd;
21
+ transform({
22
+ filename: 'foo.js',
23
+ src: 'console.log("foo");',
24
+ plugins: [
25
+ (babel, opts, cwd) => {
26
+ pluginCwd = cwd;
27
+ return {
28
+ visitor: {
29
+ CallExpression: {
30
+ enter: (_, state) => {
31
+ visitorFilename = state.filename;
32
+ },
33
+ },
34
+ },
35
+ };
36
+ },
37
+ ],
38
+ options: {
39
+ dev: true,
40
+ enableBabelRuntime: false,
41
+ enableBabelRCLookup: false,
42
+ globalPrefix: '__metro__',
43
+ hot: false,
44
+ inlineRequires: false,
45
+ minify: false,
46
+ platform: null,
47
+ publicPath: 'test',
48
+ projectRoot: PROJECT_ROOT,
49
+ },
50
+ });
51
+ expect(pluginCwd).toEqual(PROJECT_ROOT);
52
+ expect(visitorFilename).toEqual(path.resolve(PROJECT_ROOT, 'foo.js'));
53
+ });
package/src/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  *
7
- *
7
+ * @flow
8
8
  * @format
9
9
  * @oncall react_native
10
10
  */
@@ -22,106 +22,15 @@ import type {
22
22
  MetroBabelFileMetadata,
23
23
  } from 'metro-babel-transformer';
24
24
  */
25
- const _excluded = ['projectRoot', 'extendsBabelConfigPath'],
26
- _excluded2 = ['experimentalImportSupport'];
27
- function ownKeys(object, enumerableOnly) {
28
- var keys = Object.keys(object);
29
- if (Object.getOwnPropertySymbols) {
30
- var symbols = Object.getOwnPropertySymbols(object);
31
- enumerableOnly &&
32
- (symbols = symbols.filter(function (sym) {
33
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
34
- })),
35
- keys.push.apply(keys, symbols);
36
- }
37
- return keys;
38
- }
39
- function _objectSpread(target) {
40
- for (var i = 1; i < arguments.length; i++) {
41
- var source = null != arguments[i] ? arguments[i] : {};
42
- i % 2
43
- ? ownKeys(Object(source), !0).forEach(function (key) {
44
- _defineProperty(target, key, source[key]);
45
- })
46
- : Object.getOwnPropertyDescriptors
47
- ? Object.defineProperties(
48
- target,
49
- Object.getOwnPropertyDescriptors(source),
50
- )
51
- : ownKeys(Object(source)).forEach(function (key) {
52
- Object.defineProperty(
53
- target,
54
- key,
55
- Object.getOwnPropertyDescriptor(source, key),
56
- );
57
- });
58
- }
59
- return target;
60
- }
61
- function _defineProperty(obj, key, value) {
62
- key = _toPropertyKey(key);
63
- if (key in obj) {
64
- Object.defineProperty(obj, key, {
65
- value: value,
66
- enumerable: true,
67
- configurable: true,
68
- writable: true,
69
- });
70
- } else {
71
- obj[key] = value;
72
- }
73
- return obj;
74
- }
75
- function _toPropertyKey(arg) {
76
- var key = _toPrimitive(arg, 'string');
77
- return typeof key === 'symbol' ? key : String(key);
78
- }
79
- function _toPrimitive(input, hint) {
80
- if (typeof input !== 'object' || input === null) return input;
81
- var prim = input[Symbol.toPrimitive];
82
- if (prim !== undefined) {
83
- var res = prim.call(input, hint || 'default');
84
- if (typeof res !== 'object') return res;
85
- throw new TypeError('@@toPrimitive must return a primitive value.');
86
- }
87
- return (hint === 'string' ? String : Number)(input);
88
- }
89
- function _objectWithoutProperties(source, excluded) {
90
- if (source == null) return {};
91
- var target = _objectWithoutPropertiesLoose(source, excluded);
92
- var key, i;
93
- if (Object.getOwnPropertySymbols) {
94
- var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
95
- for (i = 0; i < sourceSymbolKeys.length; i++) {
96
- key = sourceSymbolKeys[i];
97
- if (excluded.indexOf(key) >= 0) continue;
98
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
99
- target[key] = source[key];
100
- }
101
- }
102
- return target;
103
- }
104
- function _objectWithoutPropertiesLoose(source, excluded) {
105
- if (source == null) return {};
106
- var target = {};
107
- var sourceKeys = Object.keys(source);
108
- var key, i;
109
- for (i = 0; i < sourceKeys.length; i++) {
110
- key = sourceKeys[i];
111
- if (excluded.indexOf(key) >= 0) continue;
112
- target[key] = source[key];
113
- }
114
- return target;
115
- }
116
- const _require = require('@babel/core'),
117
- parseSync = _require.parseSync,
118
- transformFromAstSync = _require.transformFromAstSync;
25
+
26
+ const {parseSync, transformFromAstSync} = require('@babel/core');
119
27
  const inlineRequiresPlugin = require('babel-preset-fbjs/plugins/inline-requires');
120
28
  const crypto = require('crypto');
121
29
  const fs = require('fs');
122
30
  const makeHMRConfig = require('@react-native/babel-preset/src/configs/hmr');
123
31
  const nullthrows = require('nullthrows');
124
32
  const path = require('path');
33
+
125
34
  const cacheKeyParts = [
126
35
  fs.readFileSync(__filename),
127
36
  require('babel-preset-fbjs/package.json').version,
@@ -131,6 +40,7 @@ const cacheKeyParts = [
131
40
  function isTypeScriptSource(fileName /*: string */) {
132
41
  return !!fileName && fileName.endsWith('.ts');
133
42
  }
43
+
134
44
  function isTSXSource(fileName /*: string */) {
135
45
  return !!fileName && fileName.endsWith('.tsx');
136
46
  }
@@ -145,17 +55,20 @@ const getBabelRC = (function () {
145
55
 
146
56
  /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
147
57
  * LTI update could not be added via codemod */
148
- return function _getBabelRC(_ref) {
149
- let projectRoot = _ref.projectRoot,
150
- extendsBabelConfigPath = _ref.extendsBabelConfigPath,
151
- options = _objectWithoutProperties(_ref, _excluded);
58
+ return function _getBabelRC({
59
+ projectRoot,
60
+ extendsBabelConfigPath,
61
+ ...options
62
+ }) {
152
63
  if (babelRC != null) {
153
64
  return babelRC;
154
65
  }
66
+
155
67
  babelRC = {
156
68
  plugins: [],
157
69
  extends: extendsBabelConfigPath,
158
70
  };
71
+
159
72
  if (extendsBabelConfigPath) {
160
73
  return babelRC;
161
74
  }
@@ -167,6 +80,7 @@ const getBabelRC = (function () {
167
80
  if (projectRoot) {
168
81
  projectBabelRCPath = path.resolve(projectRoot, '.babelrc');
169
82
  }
83
+
170
84
  if (projectBabelRCPath) {
171
85
  // .babelrc.js
172
86
  if (!fs.existsSync(projectBabelRCPath)) {
@@ -191,29 +105,22 @@ const getBabelRC = (function () {
191
105
  // $FlowFixMe[incompatible-use] `extends` is missing in null or undefined.
192
106
  // $FlowFixMe[incompatible-type] `extends` is missing in null or undefined.
193
107
  if (!babelRC.extends) {
194
- const experimentalImportSupport = options.experimentalImportSupport,
195
- presetOptions = _objectWithoutProperties(options, _excluded2);
108
+ const {experimentalImportSupport, ...presetOptions} = options;
196
109
 
197
110
  // $FlowFixMe[incompatible-use] `presets` is missing in null or undefined.
198
111
  babelRC.presets = [
199
112
  [
200
113
  require('@react-native/babel-preset'),
201
- _objectSpread(
202
- _objectSpread(
203
- {
204
- projectRoot,
205
- },
206
- presetOptions,
207
- ),
208
- {},
209
- {
210
- disableImportExportTransform: experimentalImportSupport,
211
- enableBabelRuntime: options.enableBabelRuntime,
212
- },
213
- ),
114
+ {
115
+ projectRoot,
116
+ ...presetOptions,
117
+ disableImportExportTransform: experimentalImportSupport,
118
+ enableBabelRuntime: options.enableBabelRuntime,
119
+ },
214
120
  ],
215
121
  ];
216
122
  }
123
+
217
124
  return babelRC;
218
125
  };
219
126
  })();
@@ -230,6 +137,7 @@ function buildBabelConfig(
230
137
  plugins /*:: ?: Plugins*/ = [],
231
138
  ) /*: BabelCoreOptions*/ {
232
139
  const babelRC = getBabelRC(options);
140
+
233
141
  const extraConfig /*: BabelCoreOptions */ = {
234
142
  babelrc:
235
143
  typeof options.enableBabelRCLookup === 'boolean'
@@ -240,20 +148,24 @@ function buildBabelConfig(
240
148
  filename,
241
149
  highlightCode: true,
242
150
  };
243
- let config /*: BabelCoreOptions */ = _objectSpread(
244
- _objectSpread({}, babelRC),
245
- extraConfig,
246
- );
151
+
152
+ let config /*: BabelCoreOptions */ = {
153
+ ...babelRC,
154
+ ...extraConfig,
155
+ };
247
156
 
248
157
  // Add extra plugins
249
158
  const extraPlugins = [];
159
+
250
160
  if (options.inlineRequires) {
251
161
  extraPlugins.push(inlineRequiresPlugin);
252
162
  }
163
+
253
164
  const withExtrPlugins = (config.plugins = extraPlugins.concat(
254
165
  config.plugins,
255
166
  plugins,
256
167
  ));
168
+
257
169
  if (options.dev && options.hot) {
258
170
  // Note: this intentionally doesn't include the path separator because
259
171
  // I'm not sure which one it should use on Windows, and false positives
@@ -262,14 +174,20 @@ function buildBabelConfig(
262
174
  // the first one often won't be there.
263
175
  const mayContainEditableReactComponents =
264
176
  filename.indexOf('node_modules') === -1;
177
+
265
178
  if (mayContainEditableReactComponents) {
266
179
  const hmrConfig = makeHMRConfig();
267
180
  hmrConfig.plugins = withExtrPlugins.concat(hmrConfig.plugins);
268
- config = _objectSpread(_objectSpread({}, config), hmrConfig);
181
+ config = {...config, ...hmrConfig};
269
182
  }
270
183
  }
271
- return _objectSpread(_objectSpread({}, babelRC), config);
184
+
185
+ return {
186
+ ...babelRC,
187
+ ...config,
188
+ };
272
189
  }
190
+
273
191
  const transform /*: BabelTransformer['transform'] */ = ({
274
192
  filename,
275
193
  options,
@@ -280,30 +198,21 @@ const transform /*: BabelTransformer['transform'] */ = ({
280
198
  process.env.BABEL_ENV = options.dev
281
199
  ? 'development'
282
200
  : process.env.BABEL_ENV || 'production';
201
+
283
202
  try {
284
- const babelConfig = _objectSpread(
285
- _objectSpread(
286
- {
287
- // ES modules require sourceType='module' but OSS may not always want that
288
- sourceType: 'unambiguous',
289
- },
290
- buildBabelConfig(filename, options, plugins),
291
- ),
292
- {},
293
- {
294
- caller: {
295
- name: 'metro',
296
- bundler: 'metro',
297
- platform: options.platform,
298
- },
299
- ast: true,
300
- // NOTE(EvanBacon): We split the parse/transform steps up to accommodate
301
- // Hermes parsing, but this defaults to cloning the AST which increases
302
- // the transformation time by a fair amount.
303
- // You get this behavior by default when using Babel's `transform` method directly.
304
- cloneInputAst: false,
305
- },
306
- );
203
+ const babelConfig = {
204
+ // ES modules require sourceType='module' but OSS may not always want that
205
+ sourceType: 'unambiguous',
206
+ ...buildBabelConfig(filename, options, plugins),
207
+ caller: {name: 'metro', bundler: 'metro', platform: options.platform},
208
+ ast: true,
209
+
210
+ // NOTE(EvanBacon): We split the parse/transform steps up to accommodate
211
+ // Hermes parsing, but this defaults to cloning the AST which increases
212
+ // the transformation time by a fair amount.
213
+ // You get this behavior by default when using Babel's `transform` method directly.
214
+ cloneInputAst: false,
215
+ };
307
216
  const sourceAst =
308
217
  isTypeScriptSource(filename) ||
309
218
  isTSXSource(filename) ||
@@ -313,6 +222,7 @@ const transform /*: BabelTransformer['transform'] */ = ({
313
222
  babel: true,
314
223
  sourceType: babelConfig.sourceType,
315
224
  });
225
+
316
226
  const result /*: TransformResult<MetroBabelFileMetadata> */ =
317
227
  transformFromAstSync(sourceAst, src, babelConfig);
318
228
 
@@ -320,27 +230,26 @@ const transform /*: BabelTransformer['transform'] */ = ({
320
230
  if (!result) {
321
231
  /* $FlowFixMe BabelTransformer specifies that the `ast` can never be null but
322
232
  * the function returns here. Discovered when typing `BabelNode`. */
323
- return {
324
- ast: null,
325
- };
233
+ return {ast: null};
326
234
  }
327
- return {
328
- ast: nullthrows(result.ast),
329
- metadata: result.metadata,
330
- };
235
+
236
+ return {ast: nullthrows(result.ast), metadata: result.metadata};
331
237
  } finally {
332
238
  if (OLD_BABEL_ENV) {
333
239
  process.env.BABEL_ENV = OLD_BABEL_ENV;
334
240
  }
335
241
  }
336
242
  };
243
+
337
244
  function getCacheKey() {
338
245
  var key = crypto.createHash('md5');
339
246
  cacheKeyParts.forEach(part => key.update(part));
340
247
  return key.digest('hex');
341
248
  }
249
+
342
250
  const babelTransformer /*: BabelTransformer */ = {
343
251
  transform,
344
252
  getCacheKey,
345
253
  };
254
+
346
255
  module.exports = babelTransformer;
package/.babelrc DELETED
@@ -1,12 +0,0 @@
1
- {
2
- "plugins": [
3
- "@babel/plugin-proposal-object-rest-spread",
4
- "@babel/plugin-transform-async-to-generator",
5
- "@babel/plugin-transform-destructuring",
6
- "@babel/plugin-transform-flow-strip-types",
7
- "@babel/plugin-syntax-dynamic-import",
8
- "@babel/plugin-proposal-class-properties",
9
- "@babel/plugin-proposal-nullish-coalescing-operator",
10
- "@babel/plugin-proposal-optional-chaining"
11
- ]
12
- }
package/.prettierrc DELETED
@@ -1,8 +0,0 @@
1
- {
2
- "arrowParens": "avoid",
3
- "bracketSameLine": true,
4
- "bracketSpacing": false,
5
- "requirePragma": true,
6
- "singleQuote": true,
7
- "trailingComma": "all"
8
- }
package/BUCK DELETED
@@ -1,16 +0,0 @@
1
- load("@fbsource//tools/build_defs/third_party:yarn_defs.bzl", "yarn_workspace")
2
-
3
- oncall("react_native")
4
-
5
- yarn_workspace(
6
- name = "yarn-workspace",
7
- srcs = glob(
8
- ["src/**/*.js"],
9
- exclude = [
10
- "**/__fixtures__/**",
11
- "**/__mocks__/**",
12
- "**/__tests__/**",
13
- ],
14
- ),
15
- visibility = ["PUBLIC"],
16
- )
package/index.js.flow DELETED
@@ -1,12 +0,0 @@
1
- /**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow strict
8
- * @format
9
- * @oncall react_native
10
- */
11
-
12
- export * from './src';
package/scripts/build.js DELETED
@@ -1,114 +0,0 @@
1
- /**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @format
8
- */
9
-
10
- /**
11
- * script to build (transpile) files.
12
- *
13
- * Based off of the build script from Metro, and tweaked to run in just one
14
- * package instead of in a monorepo. Just run `build.js` and the JS files in
15
- * `src/` will be built in `lib/`, and the original source files will be copied
16
- * over as `Example.js.flow`, so consumers of this module can still make use of
17
- * type checking.
18
- *
19
- * Call this script with the `--verbose` flag to show the full output of this
20
- * script.
21
- */
22
-
23
- 'use strict';
24
-
25
- const babel = require('@babel/core');
26
- const chalk = require('chalk');
27
- const fs = require('fs');
28
- const glob = require('glob');
29
- const micromatch = require('micromatch');
30
- const mkdirp = require('mkdirp');
31
- const path = require('path');
32
- const prettier = require('prettier');
33
- const prettierConfig = JSON.parse(
34
- fs.readFileSync(path.resolve(__dirname, '..', '.prettierrc'), 'utf8'),
35
- );
36
-
37
- const SRC_DIR = 'src';
38
- const BUILD_DIR = 'lib';
39
- const JS_FILES_PATTERN = '**/*.js';
40
- const IGNORE_PATTERN = '**/__tests__/**';
41
- const PACKAGE_DIR = path.resolve(__dirname, '../');
42
-
43
- const fixedWidth = str => {
44
- const WIDTH = 80;
45
- const strs = str.match(new RegExp(`(.{1,${WIDTH}})`, 'g')) || [str];
46
- let lastString = strs[strs.length - 1];
47
- if (lastString.length < WIDTH) {
48
- lastString += Array(WIDTH - lastString.length).join(chalk.dim('.'));
49
- }
50
- return strs.slice(0, -1).concat(lastString).join('\n');
51
- };
52
-
53
- function getBuildPath(file, buildFolder) {
54
- const pkgSrcPath = path.resolve(PACKAGE_DIR, SRC_DIR);
55
- const pkgBuildPath = path.resolve(PACKAGE_DIR, BUILD_DIR);
56
- const relativeToSrcPath = path.relative(pkgSrcPath, file);
57
- return path.resolve(pkgBuildPath, relativeToSrcPath);
58
- }
59
-
60
- function buildFile(file, silent) {
61
- const destPath = getBuildPath(file, BUILD_DIR);
62
-
63
- mkdirp.sync(path.dirname(destPath));
64
- if (micromatch.isMatch(file, IGNORE_PATTERN)) {
65
- silent ||
66
- process.stdout.write(
67
- chalk.dim(' \u2022 ') +
68
- path.relative(PACKAGE_DIR, file) +
69
- ' (ignore)\n',
70
- );
71
- } else if (!micromatch.isMatch(file, JS_FILES_PATTERN)) {
72
- fs.createReadStream(file).pipe(fs.createWriteStream(destPath));
73
- silent ||
74
- process.stdout.write(
75
- chalk.red(' \u2022 ') +
76
- path.relative(PACKAGE_DIR, file) +
77
- chalk.red(' \u21D2 ') +
78
- path.relative(PACKAGE_DIR, destPath) +
79
- ' (copy)' +
80
- '\n',
81
- );
82
- } else {
83
- const transformed = prettier.format(
84
- babel.transformFileSync(file, {}).code,
85
- {
86
- ...prettierConfig,
87
- parser: 'babel',
88
- },
89
- );
90
- fs.writeFileSync(destPath, transformed);
91
- const source = fs.readFileSync(file).toString('utf-8');
92
- if (/@flow/.test(source)) {
93
- fs.createReadStream(file).pipe(fs.createWriteStream(destPath + '.flow'));
94
- }
95
- silent ||
96
- process.stdout.write(
97
- chalk.green(' \u2022 ') +
98
- path.relative(PACKAGE_DIR, file) +
99
- chalk.green(' \u21D2 ') +
100
- path.relative(PACKAGE_DIR, destPath) +
101
- '\n',
102
- );
103
- }
104
- }
105
-
106
- const srcDir = path.resolve(__dirname, '..', SRC_DIR);
107
- const pattern = path.resolve(srcDir, '**/*');
108
- const files = glob.sync(pattern, {nodir: true});
109
-
110
- process.stdout.write(fixedWidth(`${path.basename(PACKAGE_DIR)}\n`));
111
-
112
- files.forEach(file => buildFile(file, !process.argv.includes('--verbose')));
113
-
114
- process.stdout.write(`[ ${chalk.green('OK')} ]\n`);
package/src/index.js.flow DELETED
@@ -1,255 +0,0 @@
1
- /**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- * @format
9
- * @oncall react_native
10
- */
11
-
12
- // This file uses Flow comment syntax so that it may be used from source as a
13
- // transformer without itself requiring transformation, such as in
14
- // facebook/react-native's own tests.
15
-
16
- 'use strict';
17
-
18
- /*::
19
- import type {BabelCoreOptions, Plugins, TransformResult} from '@babel/core';
20
- import type {
21
- BabelTransformer,
22
- MetroBabelFileMetadata,
23
- } from 'metro-babel-transformer';
24
- */
25
-
26
- const {parseSync, transformFromAstSync} = require('@babel/core');
27
- const inlineRequiresPlugin = require('babel-preset-fbjs/plugins/inline-requires');
28
- const crypto = require('crypto');
29
- const fs = require('fs');
30
- const makeHMRConfig = require('@react-native/babel-preset/src/configs/hmr');
31
- const nullthrows = require('nullthrows');
32
- const path = require('path');
33
-
34
- const cacheKeyParts = [
35
- fs.readFileSync(__filename),
36
- require('babel-preset-fbjs/package.json').version,
37
- ];
38
-
39
- // TS detection conditions copied from @react-native/babel-preset
40
- function isTypeScriptSource(fileName /*: string */) {
41
- return !!fileName && fileName.endsWith('.ts');
42
- }
43
-
44
- function isTSXSource(fileName /*: string */) {
45
- return !!fileName && fileName.endsWith('.tsx');
46
- }
47
-
48
- /**
49
- * Return a memoized function that checks for the existence of a
50
- * project level .babelrc file, and if it doesn't exist, reads the
51
- * default RN babelrc file and uses that.
52
- */
53
- const getBabelRC = (function () {
54
- let babelRC /*: ?BabelCoreOptions */ = null;
55
-
56
- /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
57
- * LTI update could not be added via codemod */
58
- return function _getBabelRC({
59
- projectRoot,
60
- extendsBabelConfigPath,
61
- ...options
62
- }) {
63
- if (babelRC != null) {
64
- return babelRC;
65
- }
66
-
67
- babelRC = {
68
- plugins: [],
69
- extends: extendsBabelConfigPath,
70
- };
71
-
72
- if (extendsBabelConfigPath) {
73
- return babelRC;
74
- }
75
-
76
- // Let's look for a babel config file in the project root.
77
- let projectBabelRCPath;
78
-
79
- // .babelrc
80
- if (projectRoot) {
81
- projectBabelRCPath = path.resolve(projectRoot, '.babelrc');
82
- }
83
-
84
- if (projectBabelRCPath) {
85
- // .babelrc.js
86
- if (!fs.existsSync(projectBabelRCPath)) {
87
- projectBabelRCPath = path.resolve(projectRoot, '.babelrc.js');
88
- }
89
-
90
- // babel.config.js
91
- if (!fs.existsSync(projectBabelRCPath)) {
92
- projectBabelRCPath = path.resolve(projectRoot, 'babel.config.js');
93
- }
94
-
95
- // If we found a babel config file, extend our config off of it
96
- // otherwise the default config will be used
97
- if (fs.existsSync(projectBabelRCPath)) {
98
- // $FlowFixMe[incompatible-use] `extends` is missing in null or undefined.
99
- babelRC.extends = projectBabelRCPath;
100
- }
101
- }
102
-
103
- // If a babel config file doesn't exist in the project then
104
- // the default preset for react-native will be used instead.
105
- // $FlowFixMe[incompatible-use] `extends` is missing in null or undefined.
106
- // $FlowFixMe[incompatible-type] `extends` is missing in null or undefined.
107
- if (!babelRC.extends) {
108
- const {experimentalImportSupport, ...presetOptions} = options;
109
-
110
- // $FlowFixMe[incompatible-use] `presets` is missing in null or undefined.
111
- babelRC.presets = [
112
- [
113
- require('@react-native/babel-preset'),
114
- {
115
- projectRoot,
116
- ...presetOptions,
117
- disableImportExportTransform: experimentalImportSupport,
118
- enableBabelRuntime: options.enableBabelRuntime,
119
- },
120
- ],
121
- ];
122
- }
123
-
124
- return babelRC;
125
- };
126
- })();
127
-
128
- /**
129
- * Given a filename and options, build a Babel
130
- * config object with the appropriate plugins.
131
- */
132
- function buildBabelConfig(
133
- filename /*: string */,
134
- /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
135
- * LTI update could not be added via codemod */
136
- options,
137
- plugins /*:: ?: Plugins*/ = [],
138
- ) /*: BabelCoreOptions*/ {
139
- const babelRC = getBabelRC(options);
140
-
141
- const extraConfig /*: BabelCoreOptions */ = {
142
- babelrc:
143
- typeof options.enableBabelRCLookup === 'boolean'
144
- ? options.enableBabelRCLookup
145
- : true,
146
- code: false,
147
- cwd: options.projectRoot,
148
- filename,
149
- highlightCode: true,
150
- };
151
-
152
- let config /*: BabelCoreOptions */ = {
153
- ...babelRC,
154
- ...extraConfig,
155
- };
156
-
157
- // Add extra plugins
158
- const extraPlugins = [];
159
-
160
- if (options.inlineRequires) {
161
- extraPlugins.push(inlineRequiresPlugin);
162
- }
163
-
164
- const withExtrPlugins = (config.plugins = extraPlugins.concat(
165
- config.plugins,
166
- plugins,
167
- ));
168
-
169
- if (options.dev && options.hot) {
170
- // Note: this intentionally doesn't include the path separator because
171
- // I'm not sure which one it should use on Windows, and false positives
172
- // are unlikely anyway. If you later decide to include the separator,
173
- // don't forget that the string usually *starts* with "node_modules" so
174
- // the first one often won't be there.
175
- const mayContainEditableReactComponents =
176
- filename.indexOf('node_modules') === -1;
177
-
178
- if (mayContainEditableReactComponents) {
179
- const hmrConfig = makeHMRConfig();
180
- hmrConfig.plugins = withExtrPlugins.concat(hmrConfig.plugins);
181
- config = {...config, ...hmrConfig};
182
- }
183
- }
184
-
185
- return {
186
- ...babelRC,
187
- ...config,
188
- };
189
- }
190
-
191
- const transform /*: BabelTransformer['transform'] */ = ({
192
- filename,
193
- options,
194
- src,
195
- plugins,
196
- }) => {
197
- const OLD_BABEL_ENV = process.env.BABEL_ENV;
198
- process.env.BABEL_ENV = options.dev
199
- ? 'development'
200
- : process.env.BABEL_ENV || 'production';
201
-
202
- try {
203
- const babelConfig = {
204
- // ES modules require sourceType='module' but OSS may not always want that
205
- sourceType: 'unambiguous',
206
- ...buildBabelConfig(filename, options, plugins),
207
- caller: {name: 'metro', bundler: 'metro', platform: options.platform},
208
- ast: true,
209
-
210
- // NOTE(EvanBacon): We split the parse/transform steps up to accommodate
211
- // Hermes parsing, but this defaults to cloning the AST which increases
212
- // the transformation time by a fair amount.
213
- // You get this behavior by default when using Babel's `transform` method directly.
214
- cloneInputAst: false,
215
- };
216
- const sourceAst =
217
- isTypeScriptSource(filename) ||
218
- isTSXSource(filename) ||
219
- !options.hermesParser
220
- ? parseSync(src, babelConfig)
221
- : require('hermes-parser').parse(src, {
222
- babel: true,
223
- sourceType: babelConfig.sourceType,
224
- });
225
-
226
- const result /*: TransformResult<MetroBabelFileMetadata> */ =
227
- transformFromAstSync(sourceAst, src, babelConfig);
228
-
229
- // The result from `transformFromAstSync` can be null (if the file is ignored)
230
- if (!result) {
231
- /* $FlowFixMe BabelTransformer specifies that the `ast` can never be null but
232
- * the function returns here. Discovered when typing `BabelNode`. */
233
- return {ast: null};
234
- }
235
-
236
- return {ast: nullthrows(result.ast), metadata: result.metadata};
237
- } finally {
238
- if (OLD_BABEL_ENV) {
239
- process.env.BABEL_ENV = OLD_BABEL_ENV;
240
- }
241
- }
242
- };
243
-
244
- function getCacheKey() {
245
- var key = crypto.createHash('md5');
246
- cacheKeyParts.forEach(part => key.update(part));
247
- return key.digest('hex');
248
- }
249
-
250
- const babelTransformer /*: BabelTransformer */ = {
251
- transform,
252
- getCacheKey,
253
- };
254
-
255
- module.exports = babelTransformer;