|
| 1 | +import { spawn, execSync } from "child_process"; |
1 | 2 | import { defineConfig } from "vite";
|
2 | 3 | import react from "@vitejs/plugin-react";
|
3 | 4 |
|
| 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 | + |
4 | 70 | // https://vitejs.dev/config/
|
5 | 71 | export default defineConfig({
|
6 | 72 | plugins: [
|
7 | 73 | react({
|
8 | 74 | include: ["**/*.res.mjs"],
|
9 | 75 | }),
|
| 76 | + rescript() |
10 | 77 | ],
|
11 | 78 | });
|
0 commit comments