/
configuration.ts
412 lines (364 loc) · 10.9 KB
/
configuration.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
import {
convertNxGenerator,
formatFiles,
generateFiles,
GeneratorCallback,
joinPathFragments,
logger,
offsetFromRoot,
readJson,
readProjectConfiguration,
toJS,
Tree,
updateJson,
updateProjectConfiguration,
writeJson,
} from '@nrwl/devkit';
import { runTasksInSerial } from '@nrwl/workspace/src/utilities/run-tasks-in-serial';
import { Linter } from '@nrwl/linter';
import { join } from 'path';
import {
isFramework,
readCurrentWorkspaceStorybookVersionFromGenerator,
TsConfig,
} from '../../utils/utilities';
import { cypressProjectGenerator } from '../cypress-project/cypress-project';
import { StorybookConfigureSchema } from './schema';
import { initGenerator } from '../init/init';
import { checkAndCleanWithSemver } from '@nrwl/workspace/src/utilities/version-utils';
import { gte } from 'semver';
import { findStorybookAndBuildTargets } from '../../executors/utils';
import { getRootTsConfigPathInTree } from '@nrwl/workspace/src/utilities/typescript';
export async function configurationGenerator(
tree: Tree,
rawSchema: StorybookConfigureSchema
) {
const schema = normalizeSchema(rawSchema);
const tasks: GeneratorCallback[] = [];
const workspaceStorybookVersion = getCurrentWorkspaceStorybookVersion(tree);
const { projectType, targets } = readProjectConfiguration(tree, schema.name);
const { buildTarget } = findStorybookAndBuildTargets(targets);
const initTask = await initGenerator(tree, {
uiFramework: schema.uiFramework,
});
tasks.push(initTask);
createRootStorybookDir(tree, schema.js, workspaceStorybookVersion);
createProjectStorybookDir(
tree,
schema.name,
schema.uiFramework,
schema.js,
workspaceStorybookVersion
);
configureTsProjectConfig(tree, schema);
configureTsSolutionConfig(tree, schema);
updateLintConfig(tree, schema);
addStorybookTask(tree, schema.name, schema.uiFramework, buildTarget);
if (schema.configureCypress) {
if (projectType !== 'application') {
const cypressTask = await cypressProjectGenerator(tree, {
name: schema.name,
js: schema.js,
linter: schema.linter,
directory: schema.cypressDirectory,
standaloneConfig: schema.standaloneConfig,
});
tasks.push(cypressTask);
} else {
logger.warn('There is already an e2e project setup');
}
}
if (workspaceStorybookVersion !== '6') {
logger.warn(
`It looks like you're using Storybook version 5.
Please note that starting with Nx version 14, Nx will drop support for Storybook version 5.
Before upgrading to Nx 14, please make sure you have migrated your Storybook configurations
to the latest version of Storybook.
For more information, please take a look at our upgrade guide:
${
rawSchema.uiFramework === '@storybook/angular'
? 'https://nx.dev/storybook/upgrade-storybook-v6-angular'
: 'https://nx.dev/storybook/upgrade-storybook-v6-react'
}
`
);
}
await formatFiles(tree);
return runTasksInSerial(...tasks);
}
function normalizeSchema(
schema: StorybookConfigureSchema
): StorybookConfigureSchema {
const defaults = {
configureCypress: true,
linter: Linter.TsLint,
js: false,
};
return {
...defaults,
...schema,
};
}
function createRootStorybookDir(
tree: Tree,
js: boolean,
workspaceStorybookVersion: string
) {
if (tree.exists('.storybook')) {
logger.warn(
`.storybook folder already exists at root! Skipping generating files in it.`
);
return;
}
logger.debug(
`adding .storybook folder to the root directory -
based on the Storybook version installed (v${workspaceStorybookVersion}), we'll bootstrap a scaffold for that particular version.`
);
const templatePath = join(
__dirname,
workspaceStorybookVersion === '6' ? './root-files' : './root-files-5'
);
generateFiles(tree, templatePath, '', {
rootTsConfigPath: getRootTsConfigPathInTree(tree),
});
if (js) {
toJS(tree);
}
}
function createProjectStorybookDir(
tree: Tree,
projectName: string,
uiFramework: StorybookConfigureSchema['uiFramework'],
js: boolean,
workspaceStorybookVersion: string
) {
/**
* Here, same as above
* Check storybook version
* and use the correct folder
* lib-files-5 or lib-files-6
*/
const { root, projectType } = readProjectConfiguration(tree, projectName);
const projectDirectory = projectType === 'application' ? 'app' : 'lib';
const storybookRoot = join(root, '.storybook');
if (tree.exists(storybookRoot)) {
logger.warn(
`.storybook folder already exists for ${projectName}! Skipping generating files in it.`
);
return;
}
logger.debug(
`adding .storybook folder to ${projectDirectory} - using Storybook version ${workspaceStorybookVersion}`
);
const templatePath = join(
__dirname,
workspaceStorybookVersion === '6' ? './project-files' : './project-files-5'
);
generateFiles(tree, templatePath, root, {
tmpl: '',
uiFramework,
offsetFromRoot: offsetFromRoot(root),
rootTsConfigPath: getRootTsConfigPathInTree(tree),
projectType: projectDirectory,
useWebpack5:
uiFramework === '@storybook/angular' ||
uiFramework === '@storybook/react',
existsRootWebpackConfig: tree.exists('.storybook/webpack.config.js'),
});
if (js) {
toJS(tree);
}
}
function getTsConfigPath(
tree: Tree,
projectName: string,
path?: string
): string {
const { root, projectType } = readProjectConfiguration(tree, projectName);
return join(
root,
path && path.length > 0
? path
: projectType === 'application'
? 'tsconfig.app.json'
: 'tsconfig.lib.json'
);
}
function configureTsProjectConfig(
tree: Tree,
schema: StorybookConfigureSchema
) {
const { name: projectName } = schema;
let tsConfigPath: string;
let tsConfigContent: TsConfig;
try {
tsConfigPath = getTsConfigPath(tree, projectName);
tsConfigContent = readJson<TsConfig>(tree, tsConfigPath);
} catch {
/**
* Custom app configurations
* may contain a tsconfig.json
* instead of a tsconfig.app.json.
*/
tsConfigPath = getTsConfigPath(tree, projectName, 'tsconfig.json');
tsConfigContent = readJson<TsConfig>(tree, tsConfigPath);
}
if (
!tsConfigContent.exclude.includes('**/*.stories.ts') &&
!tsConfigContent.exclude.includes('**/*.stories.js')
) {
tsConfigContent.exclude = [
...(tsConfigContent.exclude || []),
'**/*.stories.ts',
'**/*.stories.js',
...(isFramework('react', schema) || isFramework('react-native', schema)
? ['**/*.stories.jsx', '**/*.stories.tsx']
: []),
];
}
writeJson(tree, tsConfigPath, tsConfigContent);
}
function configureTsSolutionConfig(
tree: Tree,
schema: StorybookConfigureSchema
) {
const { name: projectName } = schema;
const { root } = readProjectConfiguration(tree, projectName);
const tsConfigPath = join(root, 'tsconfig.json');
const tsConfigContent = readJson<TsConfig>(tree, tsConfigPath);
if (
!tsConfigContent.references
.map((reference) => reference.path)
.includes('./.storybook/tsconfig.json')
) {
tsConfigContent.references = [
...(tsConfigContent.references || []),
{
path: './.storybook/tsconfig.json',
},
];
}
writeJson(tree, tsConfigPath, tsConfigContent);
}
/**
* When adding storybook we need to inform TSLint or ESLint
* of the additional tsconfig.json file which will be the only tsconfig
* which includes *.stories files.
*
* For TSLint this is done via the builder config, for ESLint this is
* done within the .eslintrc.json file.
*/
function updateLintConfig(tree: Tree, schema: StorybookConfigureSchema) {
const { name: projectName } = schema;
const { targets, root } = readProjectConfiguration(tree, projectName);
const tslintTargets = Object.values(targets).filter(
(target) => target.executor === '@angular-devkit/build-angular:tslint'
);
tslintTargets.forEach((target) => {
target.options.tsConfig = dedupe([
...target.options.tsConfig,
joinPathFragments(root, './.storybook/tsconfig.json'),
]);
});
if (tree.exists(join(root, '.eslintrc.json'))) {
updateJson(tree, join(root, '.eslintrc.json'), (json) => {
if (typeof json.parserOptions?.project === 'string') {
json.parserOptions.project = [json.parserOptions.project];
}
if (Array.isArray(json.parserOptions?.project)) {
json.parserOptions.project = dedupe([
...json.parserOptions.project,
join(root, '.storybook/tsconfig.json'),
]);
}
const overrides = json.overrides || [];
for (const o of overrides) {
if (typeof o.parserOptions?.project === 'string') {
o.parserOptions.project = [o.parserOptions.project];
}
if (Array.isArray(o.parserOptions?.project)) {
o.parserOptions.project = dedupe([
...o.parserOptions.project,
join(root, '.storybook/tsconfig.json'),
]);
}
}
return json;
});
}
}
function dedupe(arr: string[]) {
return Array.from(new Set(arr));
}
function addStorybookTask(
tree: Tree,
projectName: string,
uiFramework: string,
buildTargetForAngularProjects: string
) {
if (uiFramework === '@storybook/react-native') {
return;
}
const projectConfig = readProjectConfiguration(tree, projectName);
projectConfig.targets['storybook'] = {
executor: '@nrwl/storybook:storybook',
options: {
uiFramework,
port: 4400,
config: {
configFolder: `${projectConfig.root}/.storybook`,
},
projectBuildConfig:
uiFramework === '@storybook/angular'
? buildTargetForAngularProjects
? projectName
: `${projectName}:build-storybook`
: undefined,
},
configurations: {
ci: {
quiet: true,
},
},
};
projectConfig.targets['build-storybook'] = {
executor: '@nrwl/storybook:build',
outputs: ['{options.outputPath}'],
options: {
uiFramework,
outputPath: joinPathFragments('dist/storybook', projectName),
config: {
configFolder: `${projectConfig.root}/.storybook`,
},
projectBuildConfig:
uiFramework === '@storybook/angular'
? buildTargetForAngularProjects
? projectName
: `${projectName}:build-storybook`
: undefined,
},
configurations: {
ci: {
quiet: true,
},
},
};
updateProjectConfiguration(tree, projectName, projectConfig);
}
function getCurrentWorkspaceStorybookVersion(tree: Tree): string {
let workspaceStorybookVersion =
readCurrentWorkspaceStorybookVersionFromGenerator(tree);
if (
gte(
checkAndCleanWithSemver('@storybook/core', workspaceStorybookVersion),
'6.0.0'
)
) {
workspaceStorybookVersion = '6';
}
return workspaceStorybookVersion;
}
export default configurationGenerator;
export const configurationSchematic = convertNxGenerator(
configurationGenerator
);