-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
init-v2.ts
236 lines (207 loc) · 6.91 KB
/
init-v2.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
import { existsSync } from 'fs';
import { PackageJson } from '../../utils/package-json';
import { prerelease } from 'semver';
import { output } from '../../utils/output';
import { getPackageManagerCommand } from '../../utils/package-manager';
import { generateDotNxSetup } from './implementation/dot-nx/add-nx-scripts';
import { runNxSync } from '../../utils/child-process';
import { readJsonFile, writeJsonFile } from '../../utils/fileutils';
import { nxVersion } from '../../utils/versions';
import {
addDepsToPackageJson,
createNxJsonFile,
isMonorepo,
runInstall,
updateGitIgnore,
} from './implementation/utils';
import { prompt } from 'enquirer';
import { execSync } from 'child_process';
import { addNxToAngularCliRepo } from './implementation/angular';
import { globWithWorkspaceContext } from '../../utils/workspace-context';
import { connectExistingRepoToNxCloudPrompt } from '../connect/connect-to-nx-cloud';
import { addNxToNpmRepo } from './implementation/add-nx-to-npm-repo';
import { addNxToMonorepo } from './implementation/add-nx-to-monorepo';
import { join } from 'path';
export interface InitArgs {
interactive: boolean;
nxCloud?: boolean;
useDotNxInstallation?: boolean;
integrated?: boolean; // For Angular projects only
}
export async function initHandler(options: InitArgs): Promise<void> {
const version =
process.env.NX_VERSION ?? (prerelease(nxVersion) ? 'next' : 'latest');
if (process.env.NX_VERSION) {
output.log({ title: `Using version ${process.env.NX_VERSION}` });
}
if (!existsSync('package.json') || options.useDotNxInstallation) {
if (process.platform !== 'win32') {
console.log(
'Setting Nx up installation in `.nx`. You can run Nx commands like: `./nx --help`'
);
} else {
console.log(
'Setting Nx up installation in `.nx`. You can run Nx commands like: `./nx.bat --help`'
);
}
generateDotNxSetup(version);
// invokes the wrapper, thus invoking the initial installation process
runNxSync('');
return;
}
// TODO(jack): Remove this Angular logic once `@nx/angular` is compatible with inferred targets.
if (existsSync('angular.json')) {
await addNxToAngularCliRepo({
...options,
integrated: !!options.integrated,
});
return;
}
output.log({ title: '🧐 Checking dependencies' });
const detectPluginsResponse = await detectPlugins();
if (!detectPluginsResponse?.plugins.length) {
// If no plugins are detected/chosen, guide users to setup
// their targetDefaults correctly so their package scripts will work.
const packageJson: PackageJson = readJsonFile('package.json');
if (isMonorepo(packageJson)) {
await addNxToMonorepo({ interactive: options.interactive });
} else {
await addNxToNpmRepo({ interactive: options.interactive });
}
} else {
const useNxCloud =
options.nxCloud ??
(options.interactive
? await connectExistingRepoToNxCloudPrompt()
: false);
const repoRoot = process.cwd();
const pmc = getPackageManagerCommand();
createNxJsonFile(repoRoot, [], [], {});
updateGitIgnore(repoRoot);
addDepsToPackageJson(repoRoot, detectPluginsResponse.plugins);
output.log({ title: '📦 Installing Nx' });
runInstall(repoRoot, pmc);
output.log({ title: '🔨 Configuring plugins' });
for (const plugin of detectPluginsResponse.plugins) {
execSync(
`${pmc.exec} nx g ${plugin}:init --keepExistingVersions ${
detectPluginsResponse.updatePackageScripts
? '--updatePackageScripts'
: ''
} --no-interactive`,
{
stdio: [0, 1, 2],
cwd: repoRoot,
}
);
}
if (!detectPluginsResponse.updatePackageScripts) {
const rootPackageJsonPath = join(repoRoot, 'package.json');
const json = readJsonFile<PackageJson>(rootPackageJsonPath);
json.nx = {};
writeJsonFile(rootPackageJsonPath, json);
}
if (useNxCloud) {
output.log({ title: '🛠️ Setting up Nx Cloud' });
execSync(
`${pmc.exec} nx g nx:connect-to-nx-cloud --installationSource=nx-init --quiet --hideFormatLogs --no-interactive`,
{
stdio: [0, 1, 2],
cwd: repoRoot,
}
);
}
}
output.log({
title: '👀 Explore Your Workspace',
bodyLines: [
`Run "nx graph" to show the graph of the workspace. It will show tasks that you can run with Nx.`,
`Read this guide on exploring your workspace: https://nx.dev/core-features/explore-graph`,
],
});
}
const npmPackageToPluginMap: Record<string, string> = {
// Generic JS tools
eslint: '@nx/eslint',
storybook: '@nx/storybook',
// Bundlers
vite: '@nx/vite',
vitest: '@nx/vite',
webpack: '@nx/webpack',
// Testing tools
jest: '@nx/jest',
cypress: '@nx/cypress',
'@playwright/test': '@nx/playwright',
// Frameworks
detox: '@nx/detox',
expo: '@nx/expo',
next: '@nx/next',
nuxt: '@nx/nuxt',
'react-native': '@nx/react-native',
'@remix-run/dev': '@nx/remix',
};
async function detectPlugins(): Promise<
undefined | { plugins: string[]; updatePackageScripts: boolean }
> {
let files = ['package.json'].concat(
globWithWorkspaceContext(process.cwd(), ['**/*/package.json'])
);
const detectedPlugins = new Set<string>();
for (const file of files) {
if (!existsSync(file)) continue;
let packageJson: PackageJson;
try {
packageJson = readJsonFile(file);
} catch {
// Could have malformed JSON for unit tests, etc.
continue;
}
const deps = {
...packageJson.dependencies,
...packageJson.devDependencies,
};
for (const [dep, plugin] of Object.entries(npmPackageToPluginMap)) {
if (deps[dep]) {
detectedPlugins.add(plugin);
}
}
}
const plugins = Array.from(detectedPlugins);
if (plugins.length === 0) return undefined;
output.log({
title: `Recommended Plugins:`,
bodyLines: [
`Add these Nx plugins to integrate with the tools used in your workspace.`,
],
});
const pluginsToInstall = await prompt<{ plugins: string[] }>([
{
name: 'plugins',
type: 'multiselect',
message: `Which plugins would you like to add?`,
choices: plugins.map((p) => ({ name: p, value: p })),
initial: plugins.map((_, i) => i) as unknown as number, // casting to avoid type error due to bad d.ts file from enquirer
},
]).then((r) => r.plugins);
if (pluginsToInstall?.length === 0) return undefined;
const updatePackageScripts = await prompt<{ updatePackageScripts: string }>([
{
name: 'updatePackageScripts',
type: 'autocomplete',
message: `Do you want to start using Nx in your package.json scripts?`,
choices: [
{
name: 'Yes',
},
{
name: 'No',
},
],
initial: 0,
},
]).then((r) => r.updatePackageScripts === 'Yes');
return {
plugins: pluginsToInstall,
updatePackageScripts,
};
}