/
typescriptDeclarationsPlugin.ts
83 lines (71 loc) · 2.12 KB
/
typescriptDeclarationsPlugin.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
import { spawn } from 'child_process';
import fs from 'fs';
import path from 'path';
import { logger } from '@ima/dev-utils/logger';
import { Plugin } from '../types';
export interface TypescriptDeclarationsPluginOptions {
additionalArgs?: string[];
tscPath?: string;
tsConfigPath?: string;
allowFailure?: boolean;
}
/**
* Resolves tsconfig paths in given directory and returns them.
* We always use the first one. They are sorted by their priority.
*/
function resolveTsConfigs(cwd: string) {
const tsConfigPaths = ['tsconfig.build.json', 'tsconfig.json'];
return tsConfigPaths.filter(tsConfigPath =>
fs.existsSync(path.join(cwd, tsConfigPath))
);
}
export function typescriptDeclarationsPlugin(
options: TypescriptDeclarationsPluginOptions
): Plugin {
let tsConfigPath: string | undefined;
const allowFailure = options?.allowFailure ?? true;
return async context => {
[tsConfigPath] = options?.tsConfigPath ?? resolveTsConfigs(context.cwd);
if (!tsConfigPath) {
return;
}
if (context.command === 'build') {
logger.info('Generating typescript declaration files...', {
trackTime: true,
});
}
await new Promise<void>((resolve, reject) => {
spawn(
options?.tscPath ? options.tscPath : 'tsc',
[
'--outDir',
context.config.output[0].dir,
'--project',
tsConfigPath,
'--emitDeclarationOnly',
'--declarationMap',
'--preserveWatchOutput',
...(['dev', 'link'].includes(context.command)
? ['--watch', '--incremental']
: []),
...(options?.additionalArgs ?? []),
].filter(Boolean) as string[],
{
stdio: 'inherit',
cwd: context.cwd,
shell: true,
}
)
.on('close', code => {
if (code !== 0 && !allowFailure) {
return reject('Error generating declaration files.');
}
return resolve();
})
.on('error', err => {
logger.error('Error generating declaration files.');
return reject(err);
});
});
};
}