/
angular-helpers.ts
84 lines (67 loc) · 2.28 KB
/
angular-helpers.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
import * as path from 'path';
import * as fs from 'fs';
import { pathExists } from 'fs-extra';
import { readFileAsJson, writeFileAsJson } from '../../helpers';
type TsConfig = {
extends: string;
};
export function getAngularAppTsConfigPath() {
const angularJson = readFileAsJson('angular.json', true);
const defaultProject = getDefaultProjectName(angularJson);
const tsConfigPath = angularJson.projects[defaultProject].architect.build.options.tsConfig;
if (!tsConfigPath || !fs.existsSync(path.resolve(tsConfigPath))) {
return false;
}
return tsConfigPath;
}
export function getAngularAppTsConfigJson() {
const tsConfigPath = getAngularAppTsConfigPath();
if (!tsConfigPath) {
return false;
}
return readFileAsJson(tsConfigPath, true);
}
function setStorybookTsconfigExtendsPath(tsconfigJson: TsConfig) {
const angularProjectTsConfigPath = getAngularAppTsConfigPath();
const newTsconfigJson = { ...tsconfigJson };
newTsconfigJson.extends = `../${angularProjectTsConfigPath}`;
return newTsconfigJson;
}
export function editStorybookTsConfig(tsconfigPath: string) {
let tsConfigJson;
try {
tsConfigJson = readFileAsJson(tsconfigPath);
} catch (e) {
if (e.name === 'SyntaxError' && e.message.indexOf('Unexpected token /') > -1) {
throw new Error(`Comments are disallowed in ${tsconfigPath}`);
}
throw e;
}
tsConfigJson = setStorybookTsconfigExtendsPath(tsConfigJson);
writeFileAsJson(tsconfigPath, tsConfigJson);
}
export function getDefaultProjectName(angularJson: any): string | undefined {
const { defaultProject, projects } = angularJson;
if (projects?.storybook) {
return 'storybook';
}
if (defaultProject) {
return defaultProject;
}
const firstProjectName = projects ? Object.keys(projects)[0] : undefined;
if (firstProjectName) {
return firstProjectName;
}
return undefined;
}
export function checkForProjects() {
const { projects } = readFileAsJson('angular.json', true);
if (!projects || Object.keys(projects).length === 0) {
throw new Error(
'Could not find a project in your Angular workspace. \nAdd a project and re-run the installation'
);
}
}
export async function getBaseTsConfigName() {
return (await pathExists('./tsconfig.base.json')) ? 'tsconfig.base.json' : 'tsconfig.json';
}