-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.ts
96 lines (80 loc) · 2.67 KB
/
index.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
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { EOL } from 'os';
import { resolve, join, dirname, relative } from 'path';
import { winPath } from '@vitjs/utils';
import mkdirp from 'mkdirp';
import Route from '../Route';
import { isTSFile, getGlobalFiles } from './utils';
import type { RouteOptions } from '../Route';
export interface ServiceOptions extends Omit<RouteOptions, 'paths' | 'service'> {
debug?: boolean;
cwd: string;
outDir: string;
}
export default class Service {
_customApps = ['_app.tsx', '_app.jsx', '_app.js'];
debug?: boolean;
paths: {
cwd?: string;
absSrcPath?: string;
absPagesPath?: string;
absOutputPath?: string;
absTmpPath?: string;
} = {};
route: Route;
constructor(options: ServiceOptions) {
this.debug = options.debug;
this.initPaths(options);
this.route = new Route({
routes: options.routes,
dynamicImport: options.dynamicImport,
service: this,
});
}
initPaths(options: ServiceOptions) {
const absSrcPath = winPath(resolve(options.cwd, './src'));
const absPagesPath = winPath(resolve(options.cwd, './src/pages'));
const absOutputPath = winPath(resolve(options.outDir));
const absTmpPath = winPath(resolve(options.cwd, './src/.vit'));
this.paths = {
cwd: options.cwd,
absSrcPath,
absPagesPath,
absOutputPath,
absTmpPath,
};
}
getCustomApp() {
return this._customApps.find((item) => {
return existsSync(winPath(resolve(this.paths.absSrcPath!, item)));
});
}
getReactVersion(): string {
const packageJsonPath = winPath(resolve(this.paths.cwd!, 'package.json'));
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
return packageJson.dependencies.react || packageJson.devDependencies.react;
}
writeFile({ path, content }: { path: string; content: string }) {
mkdirp.sync(dirname(path));
if (!existsSync(path) || readFileSync(path, 'utf-8') !== content) {
writeFileSync(path, content, 'utf-8');
}
}
writeTmpFile({ path, content, skipTSCheck = true }: { path: string; content: string; skipTSCheck?: boolean }) {
const absPath = join(this.paths.absTmpPath!, path);
let contentResult = content;
if (isTSFile(path) && skipTSCheck) {
// write @ts-nocheck into first line
contentResult = `// @ts-nocheck${EOL}${contentResult}`;
}
this.writeFile({
path: absPath,
content: contentResult,
});
}
dumpGlobalImports(files: string[]) {
return `${getGlobalFiles({ absSrcPath: this.paths.absSrcPath!, files })
.map((file) => `import '../${relative(this.paths.absSrcPath!, file)}';`)
.join('\n')}`;
}
}