-
Notifications
You must be signed in to change notification settings - Fork 367
/
Copy pathgh-pages.ts
84 lines (66 loc) · 2.05 KB
/
gh-pages.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 path from 'path';
import type { ServerRoute } from '@modern-js/types';
import { fs } from '@modern-js/utils';
import { logger } from '@modern-js/utils';
import type { CreatePreset } from './platform';
async function reorganizeHtmlFiles(
routes: ServerRoute[],
baseDir: string,
baseUrl = '/',
) {
if (!routes || !Array.isArray(routes)) {
logger.error('Invalid server routes');
return;
}
await fs.ensureDir(baseDir);
const baseUrlRegexp = new RegExp(`^${baseUrl}\\/?`);
const collectedEntryPaths = new Set<string>();
const copyPromises = routes.map(async route => {
const { urlPath, entryPath } = route;
if (!entryPath) {
logger.warn(`Route ${urlPath} does not specify entryPath, skipping`);
return;
}
if (collectedEntryPaths.has(entryPath)) {
return;
}
collectedEntryPaths.add(entryPath);
const sourceHtmlPath = path.join(baseDir, entryPath);
if (!(await fs.pathExists(sourceHtmlPath))) {
logger.error(`Source HTML file does not exist: ${sourceHtmlPath}`);
return;
}
const targetDir = urlPath.replace(baseUrlRegexp, '');
await fs.ensureDir(path.dirname(targetDir));
const targetHtmlPath = path.join(baseDir, targetDir, 'index.html');
try {
await fs.move(sourceHtmlPath, targetHtmlPath);
} catch (error: any) {
logger.error(`Failed to copy HTML file: ${error.message}`);
}
});
await Promise.all(copyPromises);
}
export const createGhPagesPreset: CreatePreset = (appContext, modernConfig) => {
const { serverRoutes, appDirectory, distDirectory } = appContext;
const {
server: { baseUrl },
} = modernConfig;
const outputDirectory = path.join(appDirectory, '.output');
return {
name: 'gh-pages',
async prepare() {
await fs.remove(outputDirectory);
},
async writeOutput() {
await fs.copy(distDirectory, outputDirectory);
},
async end() {
await reorganizeHtmlFiles(
serverRoutes,
outputDirectory,
Array.isArray(baseUrl) ? baseUrl[0] : baseUrl,
);
},
};
};