forked from nrwl/nx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
add-nx-to-nest.ts
468 lines (400 loc) · 12.3 KB
/
add-nx-to-nest.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
import * as enquirer from 'enquirer';
import { unlinkSync, writeFileSync } from 'fs-extra';
import { join } from 'path';
import { InitArgs } from '../init-v1';
import { NxJsonConfiguration } from '../../../config/nx-json';
import { ProjectConfiguration } from '../../../config/workspace-json-project-json';
import {
fileExists,
readJsonFile,
writeJsonFile,
} from '../../../utils/fileutils';
import { output } from '../../../utils/output';
import { PackageJson } from '../../../utils/package-json';
import { getPackageManagerCommand } from '../../../utils/package-manager';
import {
addDepsToPackageJson,
createNxJsonFile,
initCloud,
markRootPackageJsonAsNxProjectLegacy,
printFinalMessage,
runInstall,
updateGitIgnore,
} from './utils';
import { nxVersion } from '../../../utils/versions';
import { connectExistingRepoToNxCloudPrompt } from '../../connect/connect-to-nx-cloud';
type Options = Pick<InitArgs, 'nxCloud' | 'interactive' | 'cacheable'>;
type NestCLIConfiguration = any;
export async function addNxToNest(options: Options, packageJson: PackageJson) {
const repoRoot = process.cwd();
output.log({ title: '🐳 Nx initialization' });
// we check upstream that nest-cli.json exists before it reaches this function
// so it is guaranteed to be here
const nestCliJson = readJsonFile(
join(repoRoot, 'nest-cli.json')
) as NestCLIConfiguration;
const nestCLIConfiguration = mergeWithDefaultConfig(nestCliJson);
// For NestJS CLI Monorepo, this property is always "true"
if (nestCLIConfiguration.monorepo) {
// TODO: update message for NestJS CLI Monorepo support
output.log({ title: 'NestCLI Monorepo support is coming soon' });
return;
}
const isJS = nestCLIConfiguration.language === 'js';
const nestCacheableScripts = ['build', 'lint', 'test'];
const nestIgnoreScripts = [
'start',
'start:dev',
'start:debug',
'test:cov',
'test:watch',
];
const scripts = Object.keys(packageJson.scripts ?? {}).filter((s) => {
if (nestCacheableScripts.includes(s) || nestIgnoreScripts.includes(s)) {
return false;
}
return !s.startsWith('pre') && !s.startsWith('post');
});
let cacheableOperations: string[];
let scriptOutputs = {};
let useNxCloud: boolean;
if (options.interactive && scripts.length > 0) {
output.log({
title:
'🧑🔧 Please answer the following questions about the scripts found in your package.json in order to generate task runner configuration',
});
cacheableOperations = (
(await enquirer.prompt([
{
type: 'multiselect',
name: 'cacheableOperations',
message:
'Which of the following scripts are cacheable? (Produce the same output given the same input, e.g. build, test and lint usually are, serve and start are not)',
choices: scripts,
},
])) as any
).cacheableOperations;
for (const scriptName of cacheableOperations) {
scriptOutputs[scriptName] = (
await enquirer.prompt([
{
type: 'input',
name: scriptName,
message: `Does the "${scriptName}" script create any outputs? If not, leave blank, otherwise provide a path (e.g. dist, lib, build, coverage)`,
},
])
)[scriptName];
}
useNxCloud =
options.nxCloud ?? (await connectExistingRepoToNxCloudPrompt());
} else {
cacheableOperations = options.cacheable ?? [];
useNxCloud =
options.nxCloud ??
(options.interactive
? await connectExistingRepoToNxCloudPrompt()
: false);
}
createNxJsonFile(
repoRoot,
[],
[...cacheableOperations, ...nestCacheableScripts],
scriptOutputs
);
const pmc = getPackageManagerCommand();
updateGitIgnore(repoRoot);
addDepsToPackageJson(repoRoot);
addNestPluginToPackageJson(repoRoot);
markRootPackageJsonAsNxProjectLegacy(repoRoot, cacheableOperations, pmc);
createProjectJson(repoRoot, packageJson, nestCLIConfiguration);
removeFile(repoRoot, 'nest-cli.json');
updatePackageJsonScripts(repoRoot, isJS);
if (!isJS) {
updateTsConfig(repoRoot, nestCLIConfiguration.sourceRoot);
}
output.log({ title: '📦 Installing dependencies' });
runInstall(repoRoot);
if (useNxCloud) {
output.log({ title: '🛠️ Setting up Nx Cloud' });
initCloud(repoRoot, 'nx-init-nest');
}
printFinalMessage({
learnMoreLink: 'https://nx.dev/recipes/adopting-nx/adding-to-monorepo',
});
}
function addNestPluginToPackageJson(repoRoot: string) {
const path = join(repoRoot, `package.json`);
const json: PackageJson = readJsonFile(path);
json.devDependencies['@nx/nest'] = nxVersion;
json.devDependencies['@nx/jest'] = nxVersion;
writeJsonFile(path, json);
}
function createProjectJson(
repoRoot: string,
packageJson: PackageJson,
nestCLIOptions: NestCLIConfiguration
) {
const packageName = packageJson.name;
const path = join(repoRoot, 'project.json');
const json: ProjectConfiguration = {
name: packageName,
root: '.',
sourceRoot: nestCLIOptions.sourceRoot,
projectType: 'application',
targets: {},
tags: [],
};
json['$schema'] = 'node_modules/nx/schemas/project-schema.json';
if (nestCLIOptions.language !== 'js') {
json.targets['serve'] = {
executor: '@nx/js:node',
options: {
buildTarget: `${packageName}:build`,
},
};
console.log(nestCLIOptions);
if (nestCLIOptions.webpackOptions) {
json.targets['build'] = {
executor: '@nx/webpack:webpack',
outputs: ['{options.outputPath}'],
options: {
target: 'node',
compiler: 'tsc',
outputPath: `dist/${packageName}`,
main: join(nestCLIOptions.sourceRoot, nestCLIOptions.entryFile),
tsConfig: 'tsconfig.build.json',
},
configurations: {
production: {
optimization: true,
extractLicenses: true,
inspect: false,
},
},
};
json.targets['serve'] = {
...json.targets['serve'],
configurations: {
production: {
buildTarget: `${packageName}:build:production`,
},
},
};
} else {
json.targets['build'] = {
executor: '@nx/js:tsc',
outputs: ['{options.outputPath}'],
options: {
outputPath: `dist/${packageName}`,
main: join(nestCLIOptions.sourceRoot, nestCLIOptions.entryFile),
tsConfig: 'tsconfig.build.json',
},
};
json.targets['serve'] = {
...json.targets['serve'],
configurations: {
debug: {
inspect: 'inspect',
},
},
};
// if we're using nrwl/js, then we add nrwl/js analyzeSourceFiles to nx.json
addNrwlJsPluginsConfig(repoRoot);
}
// lint
json.targets['lint'] = {
executor: '@nx/eslint:lint',
options: {
lintFilePatterns: ['./src', './test'],
},
};
// test and e2e
addJestTargets(repoRoot, packageName, json, packageJson);
}
writeJsonFile(path, json);
}
function getJestOptions(
isE2E: boolean,
repoRoot: string,
packageName: string,
existingOptions?: Record<string, unknown>
) {
// try get the e2e json if we find it
if (isE2E && !existingOptions) {
try {
existingOptions = readJsonFile(join(repoRoot, 'test/jest-e2e.json'));
removeFile(repoRoot, 'test/jest-e2e.json');
} catch (e) {}
}
const jestOptions = existingOptions || {
moduleFileExtensions: ['js', 'json', 'ts'],
testEnvironment: 'node',
transform: { '^.+\\.(t|j)s$': 'ts-jest' },
};
jestOptions['displayName'] = isE2E ? `${packageName}-e2e` : packageName;
// remove rootDir and testRegex, we'll use testMatch instead since we'll have the
// root jest.preset.js in the root instead of 'src'
delete jestOptions['rootDir'];
delete jestOptions['testRegex'];
jestOptions['testMatch'] = isE2E
? ['<rootDir>/test/**/?(*.)+(e2e-spec|e2e-test).[jt]s?(x)']
: ['<rootDir>/src/**/*(*.)@(spec|test).[jt]s?(x)'];
// set coverage directory for unit test
if (!isE2E) {
jestOptions['coverageDirectory'] = `./coverage/${packageName}`;
}
return jestOptions;
}
function tryCreateJestPreset(repoRoot: string) {
const jestPresetPath = join(repoRoot, 'jest.preset.js');
if (!fileExists(jestPresetPath)) {
writeFileSync(
jestPresetPath,
`
const nxPreset = require('@nx/jest/preset').default;
module.exports = {...nxPreset};
`,
'utf8'
);
return true;
}
return false;
}
function addJestTargets(
repoRoot: string,
packageName: string,
projectJson: ProjectConfiguration,
packageJson: PackageJson
) {
const unitTestOptions = getJestOptions(
false,
repoRoot,
packageName,
packageJson['jest']
);
const unitTestConfigPath = 'jest.config.ts';
const e2eTestOptions = getJestOptions(true, repoRoot, packageName);
const e2eTestConfigPath = 'jest.e2e-config.ts';
const isPresetCreated = tryCreateJestPreset(repoRoot);
if (isPresetCreated) {
unitTestOptions['preset'] = e2eTestOptions['preset'] = './jest.preset.js';
}
writeFileSync(
unitTestConfigPath,
`export default ${JSON.stringify(unitTestOptions, null, 2)}`,
'utf8'
);
writeFileSync(
e2eTestConfigPath,
`export default ${JSON.stringify(e2eTestOptions, null, 2)}`,
'utf8'
);
projectJson.targets['test'] = {
executor: '@nx/jest:jest',
outputs: [`{workspaceRoot}/coverage/${packageName}`],
options: {
passWithNoTests: true,
jestConfig: unitTestConfigPath,
},
};
projectJson.targets['e2e'] = {
executor: '@nx/jest:jest',
options: {
passWithNoTests: true,
jestConfig: e2eTestConfigPath,
},
};
// remove jest options from package.json
delete packageJson['jest'];
}
function addNrwlJsPluginsConfig(repoRoot: string) {
const path = join(repoRoot, 'nx.json');
const json: NxJsonConfiguration = readJsonFile(path);
if (!json.pluginsConfig) {
json.pluginsConfig = {
'@nx/js': {
analyzeSourceFiles: true,
},
};
}
writeJsonFile(path, json);
}
function updatePackageJsonScripts(repoRoot: string, isJS: boolean) {
const path = join(repoRoot, `package.json`);
const json: PackageJson = readJsonFile(path);
if (json.scripts['build']) {
json.scripts['build'] = 'nx build';
}
if (json.scripts['lint']) {
json.scripts['lint'] = 'nx lint';
}
if (json.scripts['start:debug']) {
json.scripts['start:debug'] = 'nx serve --configuration=debug';
}
if (json.scripts['test']) {
json.scripts['test'] = 'nx test';
}
if (json.scripts['test:cov']) {
delete json.scripts['test:cov'];
}
if (json.scripts['test:watch']) {
delete json.scripts['test:watch'];
}
if (json.scripts['test:e2e']) {
delete json.scripts['test:e2e'];
json.scripts['e2e'] = 'nx e2e';
}
if (!isJS) {
if (json.scripts['start']) {
json.scripts['start'] = 'nx serve';
}
if (json.scripts['start:dev']) {
// same as nx serve
delete json.scripts['start:dev'];
}
}
writeJsonFile(path, json);
}
function updateTsConfig(repoRoot: string, sourceRoot: string) {
const path = join(repoRoot, `tsconfig.build.json`);
const json = readJsonFile(path);
// we add include to the tsconfig.build because our executor runs tsc with
// generated tsconfig which is in `tmp/**.generated.json`. By default, tsc
// cannot find the default source files anymore.
if (!json.include) json.include = [];
json.include.push(`${sourceRoot}/**/*.ts`);
writeJsonFile(path, json);
}
function removeFile(repoRoot: string, file: string) {
const path = join(repoRoot, file);
unlinkSync(path);
}
function mergeWithDefaultConfig(config: NestCLIConfiguration) {
const defaultNestCliConfigurations = {
language: 'ts',
sourceRoot: 'src',
collection: '@nestjs/schematics',
entryFile: 'main',
projects: {},
monorepo: false,
compilerOptions: {
tsConfigPath: 'tsconfig.build.json',
webpack: false,
webpackConfigPath: 'webpack.config.js',
plugins: [],
assets: [],
},
generateOptions: {},
} as NestCLIConfiguration;
if (config.compilerOptions) {
return {
...defaultNestCliConfigurations,
...config,
compilerOptions: {
...defaultNestCliConfigurations.compilerOptions,
...config.compilerOptions,
},
};
}
return { ...defaultNestCliConfigurations, ...config };
}