/
init.ts
114 lines (97 loc) · 2.76 KB
/
init.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
import {
addDependenciesToPackageJson,
convertNxGenerator,
GeneratorCallback,
removeDependenciesFromPackageJson,
stripIndents,
Tree,
updateJson,
} from '@nrwl/devkit';
import {
babelJestVersion,
jestTypesVersion,
jestVersion,
nxVersion,
swcJestVersion,
tsJestVersion,
tslibVersion,
} from '../../utils/versions';
import { JestInitSchema } from './schema';
interface NormalizedSchema extends ReturnType<typeof normalizeOptions> {}
const schemaDefaults = {
compiler: 'tsc',
} as const;
function createJestConfig(host: Tree) {
if (!host.exists('jest.config.js')) {
host.write(
'jest.config.js',
stripIndents`
const { getJestProjects } = require('@nrwl/jest');
module.exports = {
projects: getJestProjects()
};`
);
}
if (!host.exists('jest.preset.js')) {
host.write(
'jest.preset.js',
`
const nxPreset = require('@nrwl/jest/preset');
module.exports = { ...nxPreset }`
);
}
}
function updateDependencies(tree: Tree, options: NormalizedSchema) {
const dependencies = {
tslib: tslibVersion,
};
const devDeps = {
'@nrwl/jest': nxVersion,
jest: jestVersion,
'@types/jest': jestTypesVersion,
// because the default jest-preset uses ts-jest,
// jest will throw an error if it's not installed
// even if not using it in overriding transformers
'ts-jest': tsJestVersion,
};
if (options.compiler === 'babel' || options.babelJest) {
devDeps['babel-jest'] = babelJestVersion;
// in some cases @nrwl/web will not already be present i.e. node only projects
devDeps['@nrwl/web'] = nxVersion;
} else if (options.compiler === 'swc') {
devDeps['@swc/jest'] = swcJestVersion;
}
return addDependenciesToPackageJson(tree, dependencies, devDeps);
}
function updateExtensions(host: Tree) {
if (!host.exists('.vscode/extensions.json')) {
return;
}
updateJson(host, '.vscode/extensions.json', (json) => {
json.recommendations = json.recommendations || [];
const extension = 'firsttris.vscode-jest-runner';
if (!json.recommendations.includes(extension)) {
json.recommendations.push(extension);
}
return json;
});
}
export function jestInitGenerator(tree: Tree, schema: JestInitSchema) {
const options = normalizeOptions(schema);
createJestConfig(tree);
let installTask: GeneratorCallback = () => {};
if (!options.skipPackageJson) {
removeDependenciesFromPackageJson(tree, ['@nrwl/jest'], []);
installTask = updateDependencies(tree, options);
}
updateExtensions(tree);
return installTask;
}
function normalizeOptions(options: JestInitSchema) {
return {
...schemaDefaults,
...options,
};
}
export default jestInitGenerator;
export const jestInitSchematic = convertNxGenerator(jestInitGenerator);