-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtsconfig.plugin.ts
62 lines (45 loc) · 1.63 KB
/
tsconfig.plugin.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
import fs from 'fs';
import path from 'path';
import {Plugin} from 'vite';
// modified version of: https://github.com/EdieLemoine/vite-plugin-custom-tsconfig/blob/main/src/index.ts
export interface PluginOptions {
tsConfigPath?: string;
}
const NAME = 'vite-plugin-custom-tsconfig';
const TSCONFIG_PATH = 'tsconfig.json';
const BANNER = `// GENERATED BY ${NAME} \n`;
const DELETE_TIP = `Please delete it or remove ${NAME} from your Vite config`;
const resolveFromRoot = (root: string, file: string) => {
return path.resolve(root, file);
};
const tsConfigHasBanner = (tsconfig: string) => {
const tsconfigContent = fs.readFileSync(tsconfig, 'utf8');
return tsconfigContent.startsWith(BANNER.trim());
};
const customTsConfigPlugin = (options?: PluginOptions): Plugin => {
let root: string;
const resolvedOptions: Required<PluginOptions> = {
tsConfigPath: 'tsconfig.build.json',
...options,
};
return {
name: NAME,
config(config) {
root ??= config.root ?? process.cwd();
const tsconfig = resolveFromRoot(root, TSCONFIG_PATH);
if (fs.existsSync(tsconfig) && !tsConfigHasBanner(tsconfig)) {
throw new Error(`${TSCONFIG_PATH} already exists. ${DELETE_TIP}`);
}
const customTsConfig = resolveFromRoot(
root,
resolvedOptions.tsConfigPath,
);
if (!fs.existsSync(customTsConfig)) {
throw new Error(`${resolvedOptions.tsConfigPath} does not exist.`);
}
const customTsConfigContent = fs.readFileSync(customTsConfig, 'utf8');
fs.writeFileSync(tsconfig, BANNER + customTsConfigContent);
},
};
};
export default customTsConfigPlugin;