-
Notifications
You must be signed in to change notification settings - Fork 209
/
Copy pathindex.ts
912 lines (802 loc) · 24 KB
/
index.ts
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
import path from 'path';
import fs from 'fs-extra';
import ejs from 'ejs';
import dedent from 'dedent';
import kleur from 'kleur';
import yargs from 'yargs';
import ora from 'ora';
import validateNpmPackage from 'validate-npm-package-name';
import githubUsername from 'github-username';
import prompts, { type PromptObject } from './utils/prompts';
import generateExampleApp from './utils/generateExampleApp';
import { spawn } from './utils/spawn';
const FALLBACK_BOB_VERSION = '0.20.0';
const BINARIES = [
/(gradlew|\.(jar|keystore|png|jpg|gif))$/,
/\$\.yarn(?![a-z])/,
];
const COMMON_FILES = path.resolve(__dirname, '../templates/common');
const COMMON_EXAMPLE_FILES = path.resolve(
__dirname,
'../templates/common-example'
);
const COMMON_LOCAL_FILES = path.resolve(__dirname, '../templates/common-local');
const JS_FILES = path.resolve(__dirname, '../templates/js-library');
const EXPO_FILES = path.resolve(__dirname, '../templates/expo-library');
const CPP_FILES = path.resolve(__dirname, '../templates/cpp-library');
const EXAMPLE_FILES = path.resolve(__dirname, '../templates/example-legacy');
const NATIVE_COMMON_FILES = path.resolve(
__dirname,
'../templates/native-common'
);
const NATIVE_COMMON_EXAMPLE_FILES = path.resolve(
__dirname,
'../templates/native-common-example'
);
const NATIVE_FILES = {
module_legacy: path.resolve(__dirname, '../templates/native-library-legacy'),
module_new: path.resolve(__dirname, '../templates/native-library-new'),
module_mixed: path.resolve(__dirname, '../templates/native-library-mixed'),
view_legacy: path.resolve(__dirname, '../templates/native-view-legacy'),
view_mixed: path.resolve(__dirname, '../templates/native-view-mixed'),
view_new: path.resolve(__dirname, '../templates/native-view-new'),
} as const;
const JAVA_FILES = {
module_legacy: path.resolve(__dirname, '../templates/java-library-legacy'),
module_new: path.resolve(__dirname, '../templates/java-library-new'),
module_mixed: path.resolve(__dirname, '../templates/java-library-mixed'),
view_legacy: path.resolve(__dirname, '../templates/java-view-legacy'),
view_mixed: path.resolve(__dirname, '../templates/java-view-mixed'),
view_new: path.resolve(__dirname, '../templates/java-view-new'),
} as const;
const OBJC_FILES = {
module_common: path.resolve(__dirname, '../templates/objc-library'),
view_legacy: path.resolve(__dirname, '../templates/objc-view-legacy'),
view_mixed: path.resolve(__dirname, '../templates/objc-view-mixed'),
view_new: path.resolve(__dirname, '../templates/objc-view-new'),
} as const;
const KOTLIN_FILES = {
module_legacy: path.resolve(__dirname, '../templates/kotlin-library-legacy'),
module_new: path.resolve(__dirname, '../templates/kotlin-library-new'),
module_mixed: path.resolve(__dirname, '../templates/kotlin-library-mixed'),
view_legacy: path.resolve(__dirname, '../templates/kotlin-view-legacy'),
view_mixed: path.resolve(__dirname, '../templates/kotlin-view-mixed'),
view_new: path.resolve(__dirname, '../templates/kotlin-view-new'),
} as const;
const SWIFT_FILES = {
module_legacy: path.resolve(__dirname, '../templates/swift-library-legacy'),
view_legacy: path.resolve(__dirname, '../templates/swift-view-legacy'),
} as const;
type ArgName =
| 'slug'
| 'description'
| 'author-name'
| 'author-email'
| 'author-url'
| 'repo-url'
| 'languages'
| 'type'
| 'local'
| 'example'
| 'react-native-version';
type ProjectLanguages =
| 'java-objc'
| 'java-swift'
| 'kotlin-objc'
| 'kotlin-swift'
| 'cpp'
| 'js';
type ProjectType =
| 'module-legacy'
| 'module-new'
| 'module-mixed'
| 'view-mixed'
| 'view-new'
| 'view-legacy'
| 'library';
type Answers = {
slug: string;
description: string;
authorName: string;
authorEmail: string;
authorUrl: string;
repoUrl: string;
languages: ProjectLanguages;
type?: ProjectType;
example?: boolean;
reactNativeVersion?: string;
};
const LANGUAGE_CHOICES: {
title: string;
value: ProjectLanguages;
types: ProjectType[];
}[] = [
{
title: 'Kotlin & Objective-C',
value: 'kotlin-objc',
types: [
'module-legacy',
'module-new',
'module-mixed',
'view-mixed',
'view-new',
'view-legacy',
],
},
{
title: 'Java & Objective-C',
value: 'java-objc',
types: [
'module-legacy',
'module-new',
'module-mixed',
'view-mixed',
'view-new',
'view-legacy',
],
},
{
title: 'Kotlin & Swift',
value: 'kotlin-swift',
types: ['module-legacy', 'view-legacy'],
},
{
title: 'Java & Swift',
value: 'java-swift',
types: ['module-legacy', 'view-legacy'],
},
{
title: 'C++ for Android & iOS',
value: 'cpp',
types: ['module-legacy', 'module-mixed', 'module-new'],
},
{
title: 'JavaScript for Android, iOS & Web',
value: 'js',
types: ['library'],
},
];
const NEWARCH_DESCRIPTION = 'requires new arch (experimental)';
const BACKCOMPAT_DESCRIPTION = 'supports new arch (experimental)';
const TYPE_CHOICES: {
title: string;
value: ProjectType;
description: string;
}[] = [
{
title: 'JavaScript library',
value: 'library',
description: 'supports Expo Go and Web',
},
{
title: 'Native module',
value: 'module-legacy',
description: 'bridge for native APIs to JS',
},
{
title: 'Native view',
value: 'view-legacy',
description: 'bridge for native views to JS',
},
{
title: 'Turbo module with backward compat',
value: 'module-mixed',
description: BACKCOMPAT_DESCRIPTION,
},
{
title: 'Turbo module',
value: 'module-new',
description: NEWARCH_DESCRIPTION,
},
{
title: 'Fabric view with backward compat',
value: 'view-mixed',
description: BACKCOMPAT_DESCRIPTION,
},
{
title: 'Fabric view',
value: 'view-new',
description: NEWARCH_DESCRIPTION,
},
];
const args: Record<ArgName, yargs.Options> = {
'slug': {
description: 'Name of the npm package',
type: 'string',
},
'description': {
description: 'Description of the npm package',
type: 'string',
},
'author-name': {
description: 'Name of the package author',
type: 'string',
},
'author-email': {
description: 'Email address of the package author',
type: 'string',
},
'author-url': {
description: 'URL for the package author',
type: 'string',
},
'repo-url': {
description: 'URL for the repository',
type: 'string',
},
'languages': {
description: 'Languages you want to use',
choices: LANGUAGE_CHOICES.map(({ value }) => value),
},
'type': {
description: 'Type of library you want to develop',
choices: TYPE_CHOICES.map(({ value }) => value),
},
'react-native-version': {
description: 'Version of React Native to use, uses latest if not specified',
type: 'string',
},
'local': {
description: 'Whether to create a local library',
type: 'boolean',
},
'example': {
description: 'Whether to create an example app',
type: 'boolean',
default: true,
},
};
// FIXME: fix the type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function create(argv: yargs.Arguments<any>) {
let local = false;
if (typeof argv.local === 'boolean') {
local = argv.local;
} else {
const hasPackageJson = await fs.pathExists(
path.join(process.cwd(), 'package.json')
);
if (hasPackageJson) {
// If we're under a project with package.json, ask the user if they want to create a local library
const answers = await prompts({
type: 'confirm',
name: 'local',
message: `Looks like you're under a project folder. Do you want to create a local library?`,
initial: true,
});
local = answers.local;
}
}
let folder;
if (argv.name && !local) {
folder = path.join(process.cwd(), argv.name);
} else {
const answers = await prompts({
type: 'text',
name: 'folder',
message: `Where do you want to create the library?`,
initial:
local && argv.name && !argv.name.includes('/')
? `modules/${argv.name}`
: argv.name,
validate: (input) => {
if (!input) {
return 'Cannot be empty';
}
if (fs.pathExistsSync(path.join(process.cwd(), input))) {
return 'Folder already exists';
}
return true;
},
});
folder = path.join(process.cwd(), answers.folder);
}
if (await fs.pathExists(folder)) {
console.log(
`A folder already exists at ${kleur.blue(
folder
)}! Please specify another folder name or delete the existing one.`
);
process.exit(1);
}
try {
await spawn('npx', ['--help']);
} catch (error) {
// @ts-expect-error: TS doesn't know about `code`
if (error != null && error.code === 'ENOENT') {
console.log(
`Couldn't find ${kleur.blue(
'npx'
)}! Please install it by running ${kleur.blue('npm install -g npx')}`
);
process.exit(1);
} else {
throw error;
}
}
let name, email;
try {
name = await spawn('git', ['config', '--get', 'user.name']);
email = await spawn('git', ['config', '--get', 'user.email']);
} catch (e) {
// Ignore error
}
const basename = path.basename(folder);
const questions: Record<
ArgName,
Omit<PromptObject<keyof Answers>, 'validate'> & {
validate?: (value: string) => boolean | string;
}
> = {
'slug': {
type: 'text',
name: 'slug',
message: 'What is the name of the npm package?',
initial: validateNpmPackage(basename).validForNewPackages
? /^(@|react-native)/.test(basename)
? basename
: `react-native-${basename}`
: undefined,
validate: (input) =>
validateNpmPackage(input).validForNewPackages ||
'Must be a valid npm package name',
},
'description': {
type: 'text',
name: 'description',
message: 'What is the description for the package?',
validate: (input) => Boolean(input) || 'Cannot be empty',
},
'author-name': {
type: local ? null : 'text',
name: 'authorName',
message: 'What is the name of package author?',
initial: name,
validate: (input) => Boolean(input) || 'Cannot be empty',
},
'author-email': {
type: local ? null : 'text',
name: 'authorEmail',
message: 'What is the email address for the package author?',
initial: email,
validate: (input) =>
/^\S+@\S+$/.test(input) || 'Must be a valid email address',
},
'author-url': {
type: local ? null : 'text',
name: 'authorUrl',
message: 'What is the URL for the package author?',
// @ts-expect-error this is supported, but types are wrong
initial: async (previous: string) => {
try {
const username = await githubUsername(previous);
return `https://github.com/${username}`;
} catch (e) {
// Ignore error
}
return undefined;
},
validate: (input) => /^https?:\/\//.test(input) || 'Must be a valid URL',
},
'repo-url': {
type: local ? null : 'text',
name: 'repoUrl',
message: 'What is the URL for the repository?',
initial: (_: string, answers: Answers) => {
if (/^https?:\/\/github.com\/[^/]+/.test(answers.authorUrl)) {
return `${answers.authorUrl}/${answers.slug
.replace(/^@/, '')
.replace(/\//g, '-')}`;
}
return '';
},
validate: (input) => /^https?:\/\//.test(input) || 'Must be a valid URL',
},
'type': {
type: 'select',
name: 'type',
message: 'What type of library do you want to develop?',
choices: TYPE_CHOICES,
},
'languages': {
type: 'select',
name: 'languages',
message: 'Which languages do you want to use?',
choices: (_, values) => {
return LANGUAGE_CHOICES.filter((choice) => {
if (choice.types) {
return choice.types.includes(values.type);
}
return true;
});
},
},
};
// Validate arguments passed to the CLI
for (const [key, value] of Object.entries(argv)) {
if (value == null) {
continue;
}
const question = questions[key as ArgName];
if (question == null) {
continue;
}
let valid = question.validate ? question.validate(String(value)) : true;
// We also need to guard against invalid choices
// If we don't already have a validation message to provide a better error
if (typeof valid !== 'string' && 'choices' in question) {
const choices =
typeof question.choices === 'function'
? question.choices(undefined, argv, question)
: question.choices;
if (choices && !choices.some((choice) => choice.value === value)) {
valid = `Supported values are - ${choices.map((c) =>
kleur.green(c.value)
)}`;
}
}
if (valid !== true) {
let message = `Invalid value ${kleur.red(
String(value)
)} passed for ${kleur.blue(key)}`;
if (typeof valid === 'string') {
message += `: ${valid}`;
}
console.log(message);
process.exit(1);
}
}
const {
slug,
description,
authorName,
authorEmail,
authorUrl,
repoUrl,
type = 'module-mixed',
languages = type === 'library' ? 'js' : 'java-objc',
example: hasExample,
reactNativeVersion,
} = {
...argv,
...(await prompts(
Object.entries(questions)
.filter(([k, v]) => {
// Skip questions which are passed as parameter and pass validation
if (argv[k] != null && v.validate?.(argv[k]) !== false) {
return false;
}
// Skip questions with a single choice
if (Array.isArray(v.choices) && v.choices.length === 1) {
return false;
}
return true;
})
.map(([, v]) => {
const { type, choices } = v;
// Skip dynamic questions with a single choice
if (type === 'select' && typeof choices === 'function') {
return {
...v,
type: (prev, values, prompt) => {
const result = choices(prev, { ...argv, ...values }, prompt);
if (result && result.length === 1) {
return null;
}
return type;
},
};
}
return v;
})
)),
} as Answers;
// Get latest version of Bob from NPM
let version: string;
try {
version = await Promise.race([
new Promise<string>((resolve) => {
setTimeout(() => resolve(FALLBACK_BOB_VERSION), 1000);
}),
spawn('npm', ['view', 'react-native-builder-bob', 'dist-tags.latest']),
]);
} catch (e) {
// Fallback to a known version if we couldn't fetch
version = FALLBACK_BOB_VERSION;
}
const moduleType = type.startsWith('view-') ? 'view' : 'module';
const arch =
type === 'module-new' || type === 'view-new'
? 'new'
: type === 'module-mixed' || type === 'view-mixed'
? 'mixed'
: 'legacy';
const example =
hasExample && !local ? (type === 'library' ? 'expo' : 'native') : 'none';
const project = slug.replace(/^(react-native-|@[^/]+\/)/, '');
let namespace: string | undefined;
if (slug.startsWith('@') && slug.includes('/')) {
namespace = slug
.split('/')[0]
?.replace(/[^a-z0-9]/g, '')
.toLowerCase();
}
// Create a package identifier with specified namespace when possible
const pack = `${namespace ? `${namespace}.` : ''}${project
.replace(/[^a-z0-9]/g, '')
.toLowerCase()}`;
const options = {
bob: {
version: version || FALLBACK_BOB_VERSION,
},
project: {
slug,
description,
name:
/^[A-Z]/.test(basename) && /^[a-z0-9]+$/i.test(basename)
? // If the project name is already in PascalCase, use it as-is
basename
: // Otherwise, convert it to PascalCase and remove any non-alphanumeric characters
`${project.charAt(0).toUpperCase()}${project
.replace(/[^a-z0-9](\w)/g, (_, $1) => $1.toUpperCase())
.slice(1)}`,
package: pack,
package_dir: pack.replace(/\./g, '/'),
package_cpp: pack.replace(/\./g, '_'),
identifier: slug.replace(/[^a-z0-9]+/g, '-').replace(/^-/, ''),
native: languages !== 'js',
arch,
cpp: languages === 'cpp',
kotlin: languages === 'kotlin-objc' || languages === 'kotlin-swift',
swift: languages === 'java-swift' || languages === 'kotlin-swift',
view: moduleType === 'view',
module: moduleType === 'module',
},
author: {
name: authorName,
email: authorEmail,
url: authorUrl,
},
repo: repoUrl,
example,
year: new Date().getFullYear(),
};
const copyDir = async (source: string, dest: string) => {
await fs.mkdirp(dest);
const files = await fs.readdir(source);
for (const f of files) {
const target = path.join(
dest,
ejs.render(f.replace(/^\$/, ''), options, {
openDelimiter: '{',
closeDelimiter: '}',
})
);
const file = path.join(source, f);
const stats = await fs.stat(file);
if (stats.isDirectory()) {
await copyDir(file, target);
} else if (!BINARIES.some((r) => r.test(file))) {
const content = await fs.readFile(file, 'utf8');
await fs.writeFile(target, ejs.render(content, options));
} else {
await fs.copyFile(file, target);
}
}
};
await fs.mkdirp(folder);
if (reactNativeVersion != null) {
if (example === 'expo') {
console.warn(
`${kleur.yellow('⚠')} Ignoring --react-native-version for Expo example`
);
} else {
console.log(
`${kleur.blue('ℹ')} Using ${kleur.cyan(
`react-native@${reactNativeVersion}`
)} for the example`
);
}
}
const spinner = ora().start();
if (example !== 'none') {
spinner.text = 'Generating example app';
await generateExampleApp({
type: example,
dest: folder,
slug: options.project.slug,
projectName: options.project.name,
arch,
reactNativeVersion,
swift: options.project.swift,
});
}
spinner.text = 'Copying files';
if (local) {
await copyDir(COMMON_LOCAL_FILES, folder);
} else {
await copyDir(COMMON_FILES, folder);
if (example !== 'none') {
await copyDir(COMMON_EXAMPLE_FILES, folder);
}
}
if (languages === 'js') {
await copyDir(JS_FILES, folder);
await copyDir(EXPO_FILES, folder);
} else {
if (example !== 'none') {
await copyDir(
path.join(EXAMPLE_FILES, 'example'),
path.join(folder, 'example')
);
}
await copyDir(NATIVE_COMMON_FILES, folder);
if (example !== 'none') {
await copyDir(NATIVE_COMMON_EXAMPLE_FILES, folder);
}
if (moduleType === 'module') {
await copyDir(NATIVE_FILES[`${moduleType}_${arch}`], folder);
} else {
await copyDir(NATIVE_FILES[`${moduleType}_${arch}`], folder);
}
if (options.project.swift) {
await copyDir(SWIFT_FILES[`${moduleType}_legacy`], folder);
} else {
if (moduleType === 'module') {
await copyDir(OBJC_FILES[`${moduleType}_common`], folder);
} else {
await copyDir(OBJC_FILES[`view_${arch}`], folder);
}
}
const templateType = `${moduleType}_${arch}` as const;
if (options.project.kotlin) {
await copyDir(KOTLIN_FILES[templateType], folder);
} else {
await copyDir(JAVA_FILES[templateType], folder);
}
if (options.project.cpp) {
await copyDir(CPP_FILES, folder);
await fs.remove(path.join(folder, 'ios', `${options.project.name}.m`));
}
}
if (example !== 'none') {
// Set `react` and `react-native` versions of root `package.json` from example `package.json`
const examplePackageJson = await fs.readJSON(
path.join(folder, 'example', 'package.json')
);
const rootPackageJson = await fs.readJSON(
path.join(folder, 'package.json')
);
rootPackageJson.devDependencies.react =
examplePackageJson.dependencies.react;
rootPackageJson.devDependencies['react-native'] =
examplePackageJson.dependencies['react-native'];
await fs.writeJSON(path.join(folder, 'package.json'), rootPackageJson, {
spaces: 2,
});
}
if (!local) {
let isInGitRepo = false;
try {
isInGitRepo =
(await spawn('git', ['rev-parse', '--is-inside-work-tree'])) === 'true';
} catch (e) {
// Ignore error
}
if (!isInGitRepo) {
try {
await spawn('git', ['init'], { cwd: folder });
await spawn('git', ['branch', '-M', 'main'], { cwd: folder });
await spawn('git', ['add', '.'], { cwd: folder });
await spawn('git', ['commit', '-m', 'chore: initial commit'], {
cwd: folder,
});
} catch (e) {
// Ignore error
}
}
}
spinner.succeed(
`Project created successfully at ${kleur.yellow(
path.relative(process.cwd(), folder)
)}!\n`
);
if (local) {
let linked;
const packageManager = (await fs.pathExists(
path.join(process.cwd(), 'yarn.lock')
))
? 'yarn'
: 'npm';
const packageJsonPath = path.join(process.cwd(), 'package.json');
if (await fs.pathExists(packageJsonPath)) {
const packageJson = await fs.readJSON(packageJsonPath);
const isReactNativeProject = Boolean(
packageJson.dependencies?.['react-native']
);
if (isReactNativeProject) {
packageJson.dependencies = packageJson.dependencies || {};
packageJson.dependencies[slug] =
packageManager === 'yarn'
? `link:./${path.relative(process.cwd(), folder)}`
: `file:./${path.relative(process.cwd(), folder)}`;
await fs.writeJSON(packageJsonPath, packageJson, {
spaces: 2,
});
linked = true;
}
}
console.log(
dedent(`
${kleur.magenta(
`${kleur.bold('Get started')} with the project`
)}${kleur.gray(':')}
${
(linked
? `- Run ${kleur.blue(
`${packageManager} install`
)} to link the library\n`
: `- Link the library at ${kleur.blue(
path.relative(process.cwd(), folder)
)} based on your project setup'\n`) +
`- Run ${kleur.blue(
'pod install --project-directory=ios'
)} to install dependencies with CocoaPods\n` +
`- Run ${kleur.blue('npx react-native run-android')} or ${kleur.blue(
'npx react-native run-ios'
)} to build and run the app\n` +
`- Import from ${kleur.blue(slug)} and use it in your app.`
}
${kleur.yellow(`Good luck!`)}
`)
);
} else {
const platforms = {
ios: { name: 'iOS', color: 'cyan' },
android: { name: 'Android', color: 'green' },
...(example === 'expo'
? ({ web: { name: 'Web', color: 'blue' } } as const)
: null),
} as const;
console.log(
dedent(`
${kleur.magenta(
`${kleur.bold('Get started')} with the project`
)}${kleur.gray(':')}
${kleur.gray('$')} yarn
${Object.entries(platforms)
.map(
([script, { name, color }]) => `
${kleur[color](`Run the example app on ${kleur.bold(name)}`)}${kleur.gray(
':'
)}
${kleur.gray('$')} yarn example ${script}`
)
.join('\n')}
${kleur.yellow(
`See ${kleur.bold('CONTRIBUTING.md')} for more details. Good luck!`
)}
`)
);
}
}
yargs
.command('$0 [name]', 'create a react native library', args, create)
.demandCommand()
.recommendCommands()
.fail((message, error) => {
console.log('\n');
if (error) {
console.log(kleur.red(error.message));
throw error;
}
if (message) {
console.log(kleur.red(message));
} else {
console.log(
kleur.red(`An unknown error occurred. See '--help' for usage guide.`)
);
}
process.exit(1);
})
.strict().argv;