-
Notifications
You must be signed in to change notification settings - Fork 225
Expand file tree
/
Copy pathgenerateExampleApp.ts
More file actions
370 lines (320 loc) · 10.8 KB
/
generateExampleApp.ts
File metadata and controls
370 lines (320 loc) · 10.8 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import dedent from 'dedent';
import fs from 'fs-extra';
import getLatestVersion from 'get-latest-version';
import https from 'https';
import path from 'path';
import { SUPPORTED_MONOREPO_CONFIG_VERSION } from '../constants';
import type { TemplateConfiguration } from '../template';
import sortObjectKeys from '../utils/sortObjectKeys';
import { spawn } from '../utils/spawn';
const FILES_TO_DELETE = [
'__tests__',
'.buckconfig',
'.eslintrc.js',
'.flowconfig',
'.git',
'.gitignore',
'.prettierrc.js',
'App.js',
'App.tsx',
'index.js',
'tsconfig.json',
];
const PACKAGES_TO_REMOVE = [
'@react-native/eslint-config',
'@react-native/new-app-screen',
'@tsconfig/react-native',
'@types/jest',
'@types/react-test-renderer',
'@typescript-eslint/eslint-plugin',
'@typescript-eslint/parser',
'babel-jest',
'eslint',
'jest',
'prettier',
'react-test-renderer',
'typescript',
'react-native-safe-area-context',
];
const PACKAGES_TO_ADD_EXPO_WEB = {
'@expo/metro-runtime': '~5.0.4',
'react-dom': '19.1.0',
'react-native-web': '~0.21.1',
};
const PACKAGES_TO_ADD_DEV_EXPO_NATIVE = {
'expo-dev-client': '~5.0.3',
};
export default async function generateExampleApp({
config,
root,
reactNativeVersion = 'latest',
}: {
config: TemplateConfiguration;
root: string;
reactNativeVersion: string | undefined;
}) {
const directory = path.join(root, 'example');
let args: string[] = [];
switch (config.example) {
case 'vanilla':
// `npx @react-native-community/cli init <projectName> --directory example --skip-install`
args = [
`@react-native-community/cli`,
'init',
`${config.project.name}Example`,
'--package-name',
`${config.project.package}.example`,
'--directory',
directory,
'--version',
reactNativeVersion,
'--skip-install',
'--skip-git-init',
'--pm',
'npm',
];
break;
case 'test-app':
{
// Test App requires React Native version to be a semver version
const matchedReactNativeVersion = /(\d+\.\d+[-.0-9a-z]*)/.test(
reactNativeVersion
)
? reactNativeVersion
: await getLatestVersion('react-native', {
range: reactNativeVersion,
});
if (!matchedReactNativeVersion) {
throw new Error(
`Could not find a matching version for react-native: ${reactNativeVersion}`
);
}
// `npx --package react-native-test-app@latest init --name ${projectName}Example --destination example --version ${reactNativeVersion}`
args = [
'--package',
`react-native-test-app@latest`,
'init',
'--name',
`${config.project.name}Example`,
`--destination`,
directory,
'--version',
matchedReactNativeVersion,
'--platform',
'ios',
'--platform',
'android',
];
}
break;
case 'expo':
// `npx create-expo-app example --no-install --template blank`
args = [
'create-expo-app@latest',
directory,
'--no-install',
'--template',
'blank',
];
break;
case undefined:
case null: {
// Do nothing
}
}
await spawn('npx', args, {
env: { ...process.env, npm_config_yes: 'true' },
});
// Remove unnecessary files and folders
for (const file of FILES_TO_DELETE) {
await fs.remove(path.join(directory, file));
}
// Patch the example app's package.json
const pkg = await fs.readJSON(path.join(directory, 'package.json'));
pkg.name = `${config.project.slug}-example`;
// Remove Jest config for now
delete pkg.jest;
// Make sure we have at least empty objects
// Otherwise generation will fails if package doesn't contain these fields
pkg.scripts = pkg.scripts || {};
pkg.dependencies = pkg.dependencies || {};
pkg.devDependencies = pkg.devDependencies || {};
const { scripts, dependencies, devDependencies } = pkg;
delete scripts.test;
delete scripts.lint;
const SCRIPTS_TO_ADD =
config.example === 'expo'
? {
'build:ios': `xcodebuild ONLY_ACTIVE_ARCH=YES -workspace ios/${config.project.name}Example.xcworkspace -UseNewBuildSystem=YES -scheme ${config.project.name}Example -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build -quiet`,
'build:android':
'cd android && ./gradlew assembleDebug -DtestBuildType=debug -Dorg.gradle.jvmargs=-Xmx4g',
}
: {
'build:android':
'react-native build-android --extra-params "--no-daemon --console=plain -PreactNativeArchitectures=arm64-v8a"',
'build:ios': `react-native build-ios --mode Debug`,
};
if (config.example === 'vanilla') {
Object.assign(scripts, SCRIPTS_TO_ADD);
} else if (config.example === 'test-app') {
// `react-native-test-app` doesn't bundle application by default in 'Release' mode and also `bundle` command doesn't create a directory.
// `mkdist` script should be removed after stable React Native major contains this fix: https://github.com/facebook/react-native/pull/45182.
const androidBuild = [
'npm run mkdist',
'react-native bundle --entry-file index.js --platform android --dev true --bundle-output dist/main.android.jsbundle --assets-dest dist',
SCRIPTS_TO_ADD['build:android'],
].join(' && ');
const iosBuild = [
'npm run mkdist',
'react-native bundle --entry-file index.js --platform ios --dev true --bundle-output dist/main.ios.jsbundle --assets-dest dist',
SCRIPTS_TO_ADD['build:ios'],
].join(' && ');
Object.assign(scripts, {
'build:android': androidBuild,
'build:ios': iosBuild,
});
const app = await fs.readJSON(path.join(directory, 'app.json'));
app.android = app.android || {};
app.android.package = `${config.project.package}.example`;
app.ios = app.ios || {};
app.ios.bundleIdentifier = `${config.project.package}.example`;
await fs.writeJSON(path.join(directory, 'app.json'), app, {
spaces: 2,
});
}
PACKAGES_TO_REMOVE.forEach((name) => {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete devDependencies[name];
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete dependencies[name];
});
const PACKAGES_TO_ADD_DEV = {
'react-native-builder-bob': `^${config.versions.bob}`,
'react-native-monorepo-config': `^${SUPPORTED_MONOREPO_CONFIG_VERSION}`,
};
if (
config.project.moduleConfig === 'nitro-modules' ||
config.project.viewConfig === 'nitro-view'
) {
const packagesToAddNitro = {
'react-native-nitro-modules': `^${config.versions.nitro || 'latest'}`,
};
Object.assign(dependencies, packagesToAddNitro);
}
Object.assign(devDependencies, PACKAGES_TO_ADD_DEV);
if (config.example === 'expo') {
const sdkVersion: string = dependencies.expo
.split('.')[0]
.replace(/[^\d]/, '');
let bundledNativeModules: Record<string, string>;
try {
bundledNativeModules = await new Promise((resolve, reject) => {
https
.get(
`https://raw.githubusercontent.com/expo/expo/sdk-${sdkVersion}/packages/expo/bundledNativeModules.json`,
(res) => {
let data = '';
res.on('data', (chunk: string) => (data += chunk));
res.on('end', () => {
try {
resolve(JSON.parse(data));
} catch (e) {
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
reject(e);
}
});
}
)
.on('error', reject);
});
} catch (e) {
bundledNativeModules = {};
}
if (config.project.native) {
Object.entries(PACKAGES_TO_ADD_DEV_EXPO_NATIVE).forEach(
([name, version]) => {
devDependencies[name] = bundledNativeModules[name] || version;
}
);
scripts.start = 'expo start --dev-client';
scripts.android = 'expo run:android';
scripts.ios = 'expo run:ios';
delete scripts.web;
await fs.writeFile(
path.join(directory, '.gitignore'),
dedent`
# These folders are generated with prebuild (CNG)
android/
ios/
`
);
} else {
Object.entries(PACKAGES_TO_ADD_EXPO_WEB).forEach(([name, version]) => {
dependencies[name] = bundledNativeModules[name] || version;
});
scripts.web = 'expo start --web';
}
const app = await fs.readJSON(path.join(directory, 'app.json'));
app.expo.name = `${config.project.name} Example`;
app.expo.slug = `${config.project.slug}-example`;
app.expo.android = app.expo.android || {};
app.expo.android.package = `${config.project.package}.example`;
app.expo.ios = app.expo.ios || {};
app.expo.ios.bundleIdentifier = `${config.project.package}.example`;
await fs.writeJSON(path.join(directory, 'app.json'), app, {
spaces: 2,
});
}
// Sort the deps by name to match behavior of package managers
// This way the package.json doesn't get updated when installing deps
for (const field of ['dependencies', 'devDependencies']) {
if (pkg[field]) {
pkg[field] = sortObjectKeys(pkg[field]);
}
}
await fs.writeJSON(path.join(directory, 'package.json'), pkg, {
spaces: 2,
});
if (config.example !== 'expo') {
let gradleProperties = await fs.readFile(
path.join(directory, 'android', 'gradle.properties'),
'utf8'
);
// Disable Jetifier.
// Remove this when the app template is updated.
gradleProperties = gradleProperties.replace(
'android.enableJetifier=true',
'android.enableJetifier=false'
);
// Enable new arch for iOS and Android
// iOS
// Add ENV['RCT_NEW_ARCH_ENABLED'] = 1 on top of example/ios/Podfile
const podfile = await fs.readFile(
path.join(directory, 'ios', 'Podfile'),
'utf8'
);
await fs.writeFile(
path.join(directory, 'ios', 'Podfile'),
"ENV['RCT_NEW_ARCH_ENABLED'] = '1'\n\n" + podfile
);
// Android
// Make sure newArchEnabled=true is present in android/gradle.properties
if (gradleProperties.split('\n').includes('#newArchEnabled=true')) {
gradleProperties = gradleProperties.replace(
'#newArchEnabled=true',
'newArchEnabled=true'
);
} else if (gradleProperties.split('\n').includes('newArchEnabled=false')) {
gradleProperties = gradleProperties.replace(
'newArchEnabled=false',
'newArchEnabled=true'
);
} else if (!gradleProperties.split('\n').includes('newArchEnabled=true')) {
gradleProperties += '\nnewArchEnabled=true';
}
await fs.writeFile(
path.join(directory, 'android', 'gradle.properties'),
gradleProperties
);
}
}