Skip to content

Commit 954f006

Browse files
committed
Add vite plugin
1 parent 17636f3 commit 954f006

File tree

2 files changed

+68
-7
lines changed

2 files changed

+68
-7
lines changed

templates/rescript-template-vite/README.md

+1-7
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,7 @@ This is a Vite-based template with following setup:
1111

1212
## Development
1313

14-
Run ReScript in dev mode:
15-
16-
```sh
17-
npm run res:dev
18-
```
19-
20-
In another tab, run the Vite dev server:
14+
Run the Vite dev server and ReScript in dev mode:
2115

2216
```sh
2317
npm run dev
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,78 @@
1+
import { spawn, execSync } from "child_process";
12
import { defineConfig } from "vite";
23
import react from "@vitejs/plugin-react";
34

5+
/**
6+
* Helper plugin to start and stop the ReScript compiler in the Vite pipeline.
7+
* @returns Vite plugin
8+
*/
9+
function rescript() {
10+
let rescriptProcressRef = null;
11+
let logger = { info: console.log, warn: console.warn, error: console.error };
12+
let command = "build";
13+
14+
return {
15+
name: "rescript",
16+
enforce: "pre",
17+
// Don't watch *.res files with Vite, ReScript will take care of these.
18+
config: function (config) {
19+
if (!config.server) {
20+
config.server = {};
21+
}
22+
23+
if (!config.server.watch) {
24+
config.server.watch = {};
25+
}
26+
27+
if (Array.isArray(config.server.watch.ignored)) {
28+
config.server.watch.ignored.push("**/*.res");
29+
} else {
30+
config.server.watch.ignored = ["**/*.res"];
31+
}
32+
},
33+
configResolved: async function (resolvedConfig) {
34+
logger = resolvedConfig.logger;
35+
command = resolvedConfig.command;
36+
},
37+
buildStart: async function () {
38+
if (command === "build") {
39+
logger.info(execSync("npx rescript").toString().trim());
40+
} else {
41+
rescriptProcressRef = spawn("npx", ["rescript", "-w"]);
42+
logger.info(`Spawned rescript -w`);
43+
44+
// Process standard output
45+
rescriptProcressRef.stdout.on("data", (data) => {
46+
logger.info(data.toString().trim());
47+
});
48+
49+
// Process standard error
50+
rescriptProcressRef.stderr.on("data", (data) => {
51+
logger.error(data.toString().trim());
52+
});
53+
54+
// Handle process exit
55+
rescriptProcressRef.on("close", (code) => {
56+
console.log(`ReScript process exited with code ${code || 0}`);
57+
});
58+
}
59+
},
60+
buildEnd: async function () {
61+
if (rescriptProcressRef && !rescriptProcressRef.killed) {
62+
const pid = rescriptProcressRef.pid;
63+
rescriptProcressRef.kill("SIGKILL"); // Default signal is SIGTERM
64+
logger.info(`ReScript process with PID: ${pid} has been killed`);
65+
}
66+
},
67+
};
68+
}
69+
470
// https://vitejs.dev/config/
571
export default defineConfig({
672
plugins: [
773
react({
874
include: ["**/*.res.mjs"],
975
}),
76+
rescript()
1077
],
1178
});

0 commit comments

Comments
 (0)