Skip to content

Commit

Permalink
Kill the ReScript process if applicable when bundle is closing (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
jihchi authored Sep 27, 2023
1 parent 09a3138 commit e758f57
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
21 changes: 19 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ import parseCompilerLog from './parseCompilerLog.js';

const logPrefix = chalk.cyan('[@jihchi/vite-plugin-rescript]');

async function launchReScript(watch: boolean) {
type ReScriptProcess = {
shutdown: () => void;
};

async function launchReScript(watch: boolean): Promise<ReScriptProcess> {
const cmd = watch
? 'rescript build -with-deps -w'
: 'rescript build -with-deps';
Expand Down Expand Up @@ -44,6 +48,14 @@ async function launchReScript(watch: boolean) {
} else {
await result;
}

return {
shutdown() {
if (!result.killed) {
result.kill();
}
},
};
}

interface Config {
Expand All @@ -56,6 +68,7 @@ interface Config {
export default function createReScriptPlugin(config?: Config): Plugin {
let root: string;
let usingLoader = false;
let childProcessReScript: undefined | ReScriptProcess;

// Retrieve loader config
const output = config?.loader?.output ?? './lib/es6';
Expand All @@ -82,7 +95,7 @@ export default function createReScriptPlugin(config?: Config): Plugin {
const isLocked = existsSync(path.resolve('./.bsb.lock'));

if (needReScript) {
await launchReScript(
childProcessReScript = await launchReScript(
!isLocked && (command === 'serve' || Boolean(build.watch))
);
}
Expand Down Expand Up @@ -187,5 +200,9 @@ export default function createReScriptPlugin(config?: Config): Plugin {

return;
},
async closeBundle() {
childProcessReScript?.shutdown();
return;
},
};
}
6 changes: 6 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,10 @@ describe('@jihchi/vite-plugin-rescript', () => {
expect(actual).toHaveProperty('configResolved');
expect(actual.configResolved).toBeInstanceOf(Function);
});

it('invokes closeBundle hook without crashing', async () => {
const actual = Plugin();
expect(actual).toHaveProperty('closeBundle');
await expect(actual.closeBundle()).resolves.toEqual(undefined);
});
});

0 comments on commit e758f57

Please sign in to comment.