-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vite-plugins.js
98 lines (83 loc) · 2.5 KB
/
vite-plugins.js
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
97
98
import { exec } from "child_process";
import chalk from "chalk";
const pluginName = "vite-plugin-run-command-on-demand";
const log = (message) => console.log(chalk.blue(`\n[${pluginName}]`), message);
const logError = (message) =>
console.error(chalk.blue(`\n[${pluginName}]`), chalk.red(message), "\n");
const runCommand = (command) =>
new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) {
logError(`Error executing command: ${command}\n${stderr}`);
reject(error);
} else {
log(`Command executed successfully: ${command}\n${stdout}`);
resolve();
}
});
});
const executeCommand = async (command, errorMessage) => {
if (command) {
try {
await runCommand(command);
} catch {
logError(errorMessage);
}
}
};
const isAllowedEnvironment = () => {
const env = process.env.NODE_ENV;
return env === "development" || env === "production";
};
export default function customCommandsPlugin(options) {
return {
name: pluginName,
configureServer(server) {
if (!isAllowedEnvironment()) return;
server.httpServer?.once("listening", async () => {
await executeCommand(
options.beforeServerStart,
`Error running beforeServerStart command: ${options.beforeServerStart}`
);
await executeCommand(
options.afterServerStart,
`Error running afterServerStart command: ${options.afterServerStart}`
);
});
},
async handleHotUpdate(ctx) {
if (!isAllowedEnvironment()) return ctx.modules;
const isPageReload = ctx.modules.some(
(module) => !module.isSelfAccepting
);
if (!isPageReload) {
await executeCommand(
options.onHotUpdate,
`Error running onHotUpdate command: ${options.onHotUpdate}`
);
}
return ctx.modules;
},
async buildStart() {
if (!isAllowedEnvironment()) return;
await executeCommand(
options.beforeBuild,
`Error running beforeBuild command: ${options.beforeBuild}`
);
},
async buildEnd() {
if (!isAllowedEnvironment()) return;
await executeCommand(
options.afterBuild,
`Error running afterBuild command: ${options.afterBuild}`
);
},
async closeBundle() {
if (!isAllowedEnvironment()) return;
await executeCommand(
options.closeBundle,
`Error running closeBundle command: ${options.closeBundle}`
);
},
};
}