/
cra-to-nx.ts
187 lines (148 loc) · 5.29 KB
/
cra-to-nx.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
#!/usr/bin/env node
import { fileExists } from '@nrwl/workspace/src/utilities/fileutils';
import { execSync } from 'child_process';
import {
copySync,
existsSync,
moveSync,
readJsonSync,
removeSync,
readdirSync,
} from 'fs-extra';
import { addCRAcracoScriptsToPackageJson } from './add-cra-commands-to-nx';
import { checkForUncommittedChanges } from './check-for-uncommitted-changes';
import { setupE2eProject } from './setup-e2e-project';
import { readNameFromPackageJson } from './read-name-from-package-json';
import { setupTsConfig } from './tsconfig-setup';
import { writeCracoConfig } from './write-craco-config';
import { cleanUpFiles } from './clean-up-files';
import { output } from '@nrwl/devkit';
let packageManager: string;
function checkPackageManager() {
packageManager = existsSync('yarn.lock')
? 'yarn'
: existsSync('pnpm-lock.yaml')
? 'pnpm'
: 'npm';
}
function addDependency(dep: string, dev?: boolean) {
output.log({ title: `📦 Adding dependency: ${dep}` });
if (packageManager === 'yarn') {
execSync(`yarn add ${dev ? '-D ' : ''}${dep}`, { stdio: [0, 1, 2] });
} else if (packageManager === 'pnpm') {
execSync(`pnpm i ${dev ? '--save-dev ' : ''}${dep}`, { stdio: [0, 1, 2] });
} else {
execSync(`npm i --force ${dev ? '--save-dev ' : ''}${dep}`, {
stdio: [0, 1, 2],
});
}
}
export async function createNxWorkspaceForReact(options: Record<string, any>) {
checkForUncommittedChanges();
checkPackageManager();
output.log({ title: '🐳 Nx initialization' });
let appIsJs = true;
if (fileExists(`tsconfig.json`)) {
appIsJs = false;
}
const reactAppName = readNameFromPackageJson();
const packageJson = readJsonSync('package.json');
const deps = {
...packageJson.dependencies,
...packageJson.devDependencies,
};
const isCRA5 = /^[^~]?5/.test(deps['react-scripts']);
execSync(
`npx -y create-nx-workspace@latest temp-workspace --appName=${reactAppName} --preset=react --style=css --packageManager=${packageManager}`,
{ stdio: [0, 1, 2] }
);
output.log({ title: '👋 Welcome to Nx!' });
output.log({ title: '🧹 Clearing unused files' });
copySync(`temp-workspace/apps/${reactAppName}/project.json`, 'project.json');
removeSync(`temp-workspace/apps/${reactAppName}/`);
removeSync('node_modules');
output.log({ title: '🚚 Moving your React app in your new Nx workspace' });
const requiredCraFiles = [
'project.json',
'package.json',
'src',
'public',
appIsJs ? null : 'tsconfig.json',
packageManager === 'yarn' ? 'yarn.lock' : null,
packageManager === 'pnpm' ? 'pnpm-lock.yaml' : null,
packageManager === 'npm' ? 'package-lock.json' : null,
];
const optionalCraFiles = ['README.md'];
const filesToMove = [...requiredCraFiles, ...optionalCraFiles].filter(
Boolean
);
filesToMove.forEach((f) => {
try {
moveSync(f, `temp-workspace/apps/${reactAppName}/${f}`, {
overwrite: true,
});
} catch (error) {
if (requiredCraFiles.includes(f)) {
throw error;
}
}
});
process.chdir('temp-workspace/');
output.log({ title: '🤹 Add CRA craco scripts to package.json' });
addCRAcracoScriptsToPackageJson(reactAppName);
output.log({ title: '🧑🔧 Customize webpack ' + deps['react-scripts'] });
writeCracoConfig(reactAppName, isCRA5);
output.log({
title: '🛬 Skip CRA preflight check since Nx manages the monorepo',
});
execSync(`echo "SKIP_PREFLIGHT_CHECK=true" > .env`, { stdio: [0, 1, 2] });
output.log({ title: '🧶 Add all node_modules to .gitignore' });
execSync(`echo "node_modules" >> .gitignore`, { stdio: [0, 1, 2] });
process.chdir('../');
output.log({ title: '🚚 Folder restructuring.' });
readdirSync('./temp-workspace').forEach((f) => {
moveSync(`temp-workspace/${f}`, `./${f}`, { overwrite: true });
});
output.log({ title: '🧹 Cleaning up.' });
cleanUpFiles(reactAppName);
output.log({ title: "📃 Extend the app's tsconfig.json from the base" });
setupTsConfig(reactAppName);
if (options.e2e) {
output.log({ title: '📃 Setup e2e tests' });
setupE2eProject(reactAppName);
} else {
removeSync(`apps/${reactAppName}-e2e`);
}
output.log({ title: '🙂 Please be patient, one final step remaining!' });
output.log({
title: '🧶 Adding npm packages to your new Nx workspace to support CRA',
});
addDependency('react-scripts', true);
addDependency('@testing-library/jest-dom', true);
addDependency('eslint-config-react-app', true);
addDependency('@craco/craco', true);
addDependency('web-vitals', true);
addDependency('jest-watch-typeahead', true); // Only for ts apps?
output.log({
title: '🎉 Done!',
});
output.note({
title: 'First time using Nx? Check out this interactive Nx tutorial.',
bodyLines: [
`https://nx.dev/react/tutorial/01-create-application`,
` `,
`Prefer watching videos? Check out this free Nx course on Egghead.io.`,
`https://egghead.io/playlists/scale-react-development-with-nx-4038`,
],
});
output.note({
title: 'Or, you can try the commands!',
bodyLines: [
`npx nx serve ${reactAppName}`,
`npx nx build ${reactAppName}`,
`npx nx test ${reactAppName}`,
` `,
`https://nx.dev/getting-started/intro#10-try-the-commands`,
],
});
}