@react-native/metro-babel-transformer 0.73.0-nightly-20230807-2bf59c764

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.
Files changed (2) hide show
  1. package/package.json +29 -0
  2. package/src/index.js +244 -0
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@react-native/metro-babel-transformer",
3
+ "version": "0.73.0-nightly-20230807-2bf59c764",
4
+ "description": "Babel transformer for React Native applications.",
5
+ "main": "src/index.js",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git@github.com:facebook/react-native.git",
9
+ "directory": "packages/react-native-babel-transformer"
10
+ },
11
+ "keywords": [
12
+ "transformer",
13
+ "react-native",
14
+ "metro"
15
+ ],
16
+ "license": "MIT",
17
+ "dependencies": {
18
+ "@babel/core": "^7.20.0",
19
+ "@react-native/babel-preset": "*",
20
+ "hermes-parser": "0.15.0",
21
+ "nullthrows": "^1.1.1"
22
+ },
23
+ "peerDependencies": {
24
+ "@babel/core": "*"
25
+ },
26
+ "engines": {
27
+ "node": ">=18"
28
+ }
29
+ }
package/src/index.js ADDED
@@ -0,0 +1,244 @@
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 crypto = require('crypto');
28
+ const fs = require('fs');
29
+ const makeHMRConfig = require('@react-native/babel-preset/src/configs/hmr');
30
+ const nullthrows = require('nullthrows');
31
+ const path = require('path');
32
+
33
+ const cacheKeyParts = [fs.readFileSync(__filename)];
34
+
35
+ // TS detection conditions copied from @react-native/babel-preset
36
+ function isTypeScriptSource(fileName /*: string */) {
37
+ return !!fileName && fileName.endsWith('.ts');
38
+ }
39
+
40
+ function isTSXSource(fileName /*: string */) {
41
+ return !!fileName && fileName.endsWith('.tsx');
42
+ }
43
+
44
+ /**
45
+ * Return a memoized function that checks for the existence of a
46
+ * project level .babelrc file, and if it doesn't exist, reads the
47
+ * default RN babelrc file and uses that.
48
+ */
49
+ const getBabelRC = (function () {
50
+ let babelRC /*: ?BabelCoreOptions */ = null;
51
+
52
+ /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
53
+ * LTI update could not be added via codemod */
54
+ return function _getBabelRC({
55
+ projectRoot,
56
+ extendsBabelConfigPath,
57
+ ...options
58
+ }) {
59
+ if (babelRC != null) {
60
+ return babelRC;
61
+ }
62
+
63
+ babelRC = {
64
+ plugins: [],
65
+ extends: extendsBabelConfigPath,
66
+ };
67
+
68
+ if (extendsBabelConfigPath) {
69
+ return babelRC;
70
+ }
71
+
72
+ // Let's look for a babel config file in the project root.
73
+ let projectBabelRCPath;
74
+
75
+ // .babelrc
76
+ if (projectRoot) {
77
+ projectBabelRCPath = path.resolve(projectRoot, '.babelrc');
78
+ }
79
+
80
+ if (projectBabelRCPath) {
81
+ // .babelrc.js
82
+ if (!fs.existsSync(projectBabelRCPath)) {
83
+ projectBabelRCPath = path.resolve(projectRoot, '.babelrc.js');
84
+ }
85
+
86
+ // babel.config.js
87
+ if (!fs.existsSync(projectBabelRCPath)) {
88
+ projectBabelRCPath = path.resolve(projectRoot, 'babel.config.js');
89
+ }
90
+
91
+ // If we found a babel config file, extend our config off of it
92
+ // otherwise the default config will be used
93
+ if (fs.existsSync(projectBabelRCPath)) {
94
+ // $FlowFixMe[incompatible-use] `extends` is missing in null or undefined.
95
+ babelRC.extends = projectBabelRCPath;
96
+ }
97
+ }
98
+
99
+ // If a babel config file doesn't exist in the project then
100
+ // the default preset for react-native will be used instead.
101
+ // $FlowFixMe[incompatible-use] `extends` is missing in null or undefined.
102
+ // $FlowFixMe[incompatible-type] `extends` is missing in null or undefined.
103
+ if (!babelRC.extends) {
104
+ const {experimentalImportSupport, ...presetOptions} = options;
105
+
106
+ // $FlowFixMe[incompatible-use] `presets` is missing in null or undefined.
107
+ babelRC.presets = [
108
+ [
109
+ require('@react-native/babel-preset'),
110
+ {
111
+ projectRoot,
112
+ ...presetOptions,
113
+ disableImportExportTransform: experimentalImportSupport,
114
+ enableBabelRuntime: options.enableBabelRuntime,
115
+ },
116
+ ],
117
+ ];
118
+ }
119
+
120
+ return babelRC;
121
+ };
122
+ })();
123
+
124
+ /**
125
+ * Given a filename and options, build a Babel
126
+ * config object with the appropriate plugins.
127
+ */
128
+ function buildBabelConfig(
129
+ filename /*: string */,
130
+ /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
131
+ * LTI update could not be added via codemod */
132
+ options,
133
+ plugins /*:: ?: Plugins*/ = [],
134
+ ) /*: BabelCoreOptions*/ {
135
+ const babelRC = getBabelRC(options);
136
+
137
+ const extraConfig /*: BabelCoreOptions */ = {
138
+ babelrc:
139
+ typeof options.enableBabelRCLookup === 'boolean'
140
+ ? options.enableBabelRCLookup
141
+ : true,
142
+ code: false,
143
+ cwd: options.projectRoot,
144
+ filename,
145
+ highlightCode: true,
146
+ };
147
+
148
+ let config /*: BabelCoreOptions */ = {
149
+ ...babelRC,
150
+ ...extraConfig,
151
+ };
152
+
153
+ const withExtraPlugins = (config.plugins = [
154
+ ...(config.plugins ?? []),
155
+ ...plugins,
156
+ ]);
157
+
158
+ if (options.dev && options.hot) {
159
+ // Note: this intentionally doesn't include the path separator because
160
+ // I'm not sure which one it should use on Windows, and false positives
161
+ // are unlikely anyway. If you later decide to include the separator,
162
+ // don't forget that the string usually *starts* with "node_modules" so
163
+ // the first one often won't be there.
164
+ const mayContainEditableReactComponents =
165
+ filename.indexOf('node_modules') === -1;
166
+
167
+ if (mayContainEditableReactComponents) {
168
+ const hmrConfig = makeHMRConfig();
169
+ hmrConfig.plugins = withExtraPlugins.concat(hmrConfig.plugins);
170
+ config = {...config, ...hmrConfig};
171
+ }
172
+ }
173
+
174
+ return {
175
+ ...babelRC,
176
+ ...config,
177
+ };
178
+ }
179
+
180
+ const transform /*: BabelTransformer['transform'] */ = ({
181
+ filename,
182
+ options,
183
+ src,
184
+ plugins,
185
+ }) => {
186
+ const OLD_BABEL_ENV = process.env.BABEL_ENV;
187
+ process.env.BABEL_ENV = options.dev
188
+ ? 'development'
189
+ : process.env.BABEL_ENV || 'production';
190
+
191
+ try {
192
+ const babelConfig = {
193
+ // ES modules require sourceType='module' but OSS may not always want that
194
+ sourceType: 'unambiguous',
195
+ ...buildBabelConfig(filename, options, plugins),
196
+ caller: {name: 'metro', bundler: 'metro', platform: options.platform},
197
+ ast: true,
198
+
199
+ // NOTE(EvanBacon): We split the parse/transform steps up to accommodate
200
+ // Hermes parsing, but this defaults to cloning the AST which increases
201
+ // the transformation time by a fair amount.
202
+ // You get this behavior by default when using Babel's `transform` method directly.
203
+ cloneInputAst: false,
204
+ };
205
+ const sourceAst =
206
+ isTypeScriptSource(filename) ||
207
+ isTSXSource(filename) ||
208
+ !options.hermesParser
209
+ ? parseSync(src, babelConfig)
210
+ : require('hermes-parser').parse(src, {
211
+ babel: true,
212
+ sourceType: babelConfig.sourceType,
213
+ });
214
+
215
+ const result /*: TransformResult<MetroBabelFileMetadata> */ =
216
+ transformFromAstSync(sourceAst, src, babelConfig);
217
+
218
+ // The result from `transformFromAstSync` can be null (if the file is ignored)
219
+ if (!result) {
220
+ /* $FlowFixMe BabelTransformer specifies that the `ast` can never be null but
221
+ * the function returns here. Discovered when typing `BabelNode`. */
222
+ return {ast: null};
223
+ }
224
+
225
+ return {ast: nullthrows(result.ast), metadata: result.metadata};
226
+ } finally {
227
+ if (OLD_BABEL_ENV) {
228
+ process.env.BABEL_ENV = OLD_BABEL_ENV;
229
+ }
230
+ }
231
+ };
232
+
233
+ function getCacheKey() {
234
+ var key = crypto.createHash('md5');
235
+ cacheKeyParts.forEach(part => key.update(part));
236
+ return key.digest('hex');
237
+ }
238
+
239
+ const babelTransformer /*: BabelTransformer */ = {
240
+ transform,
241
+ getCacheKey,
242
+ };
243
+
244
+ module.exports = babelTransformer;