Skip to content

Commit dd591d1

Browse files
committed
PR feedback
1 parent 6b328c9 commit dd591d1

File tree

2 files changed

+61
-51
lines changed

2 files changed

+61
-51
lines changed

README.md

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ pnpm i -D @jihchi/vite-plugin-rescript
2929
Configure your vite plugin in `vite.config.ts`:
3030

3131
```js
32-
import { defineConfig } from 'vite';
33-
import createReScriptPlugin from '@jihchi/vite-plugin-rescript';
32+
import { defineConfig } from "vite";
33+
import createReScriptPlugin from "@jihchi/vite-plugin-rescript";
3434

3535
export default defineConfig({
3636
plugins: [createReScriptPlugin()],
@@ -42,7 +42,7 @@ If you're using `require` syntax:
4242
```js
4343
const {
4444
default: createReScriptPlugin,
45-
} = require('@jihchi/vite-plugin-rescript');
45+
} = require("@jihchi/vite-plugin-rescript");
4646
```
4747

4848
## Using Loader
@@ -71,11 +71,16 @@ export default defineConfig({
7171
plugins: [
7272
createReScriptPlugin({
7373
loader: {
74-
output: './lib/js',
75-
suffix: '.mjs',
74+
output: "./lib/js",
75+
suffix: ".mjs",
7676
},
77+
78+
// Control the terminal output of the ReScript compiler.
7779
silent: false,
78-
buildArgs: '-warn-error +32+27+26+110',
80+
81+
// Optionally add additional build args to the ReScript compiler.
82+
// See https://rescript-lang.org/docs/manual/build-overview#compile-with-stricter-errors-in-ci
83+
buildArgs: "-warn-error +32+27+26+110",
7984
}),
8085
],
8186
});
@@ -92,7 +97,7 @@ since the paths to the node_modules will be generated as relative to the `lib` f
9297
For HTML entry points, it must be imported using inline JS:
9398

9499
```html
95-
<!doctype html>
100+
<!DOCTYPE html>
96101
<html lang="en">
97102
<head>
98103
<meta charset="UTF-8" />
@@ -103,7 +108,7 @@ For HTML entry points, it must be imported using inline JS:
103108
<body>
104109
<div id="root"></div>
105110
<script type="module">
106-
import '/src/Main.res';
111+
import "/src/Main.res";
107112
</script>
108113
</body>
109114
</html>
@@ -112,14 +117,14 @@ For HTML entry points, it must be imported using inline JS:
112117
If using Vite with library mode, just use the `.res` as entry point:
113118

114119
```js
115-
import { defineConfig } from 'vite';
116-
import createReScriptPlugin from '@jihchi/vite-plugin-rescript';
120+
import { defineConfig } from "vite";
121+
import createReScriptPlugin from "@jihchi/vite-plugin-rescript";
117122

118123
export default defineConfig({
119124
plugins: [createReScriptPlugin()],
120125
build: {
121126
lib: {
122-
entry: 'src/Main.res',
127+
entry: "src/Main.res",
123128
},
124129
},
125130
});

src/index.ts

Lines changed: 45 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
import { existsSync } from 'node:fs';
2-
import * as fs from 'node:fs/promises';
3-
import * as path from 'node:path';
4-
import type { Readable } from 'node:stream';
5-
import chalk from 'chalk';
6-
import { execaCommand } from 'execa';
7-
import { npmRunPathEnv } from 'npm-run-path';
8-
import type { Plugin } from 'vite';
9-
import parseCompilerLog from './parseCompilerLog.js';
10-
11-
const logPrefix = chalk.cyan('[@jihchi/vite-plugin-rescript]');
1+
import { existsSync } from "node:fs";
2+
import * as fs from "node:fs/promises";
3+
import * as path from "node:path";
4+
import type { Readable } from "node:stream";
5+
import chalk from "chalk";
6+
import { execaCommand } from "execa";
7+
import { npmRunPathEnv } from "npm-run-path";
8+
import type { Plugin } from "vite";
9+
import parseCompilerLog from "./parseCompilerLog.js";
10+
11+
const logPrefix = chalk.cyan("[@jihchi/vite-plugin-rescript]");
1212

1313
type ReScriptProcess = {
1414
shutdown: () => void;
@@ -17,11 +17,16 @@ type ReScriptProcess = {
1717
async function launchReScript(
1818
watch: boolean,
1919
silent: boolean,
20-
buildArgs: string,
20+
buildArgs: string
2121
): Promise<ReScriptProcess> {
22-
const cmd = (watch ? 'rescript watch' : 'rescript build') + ' ' + buildArgs;
22+
let cmd = watch ? "rescript watch" : "rescript build";
23+
24+
if (buildArgs) {
25+
cmd += ` ${buildArgs}`;
26+
}
27+
2328
// https://github.com/rescript-lang/rescript/blob/9676953f5b5ce96ade6909af3f23a77cd69645e9/rewatch/src/watcher.rs#L246-L258
24-
const finishSignal = 'Finished initial compilation';
29+
const finishSignal = "Finished initial compilation";
2530

2631
const result = execaCommand(cmd, {
2732
env: npmRunPathEnv(),
@@ -45,8 +50,8 @@ async function launchReScript(
4550
}
4651

4752
const { stdout, stderr } = result;
48-
stdout?.on('data', dataListener);
49-
stderr?.on('data', dataListener);
53+
stdout?.on("data", dataListener);
54+
stderr?.on("data", dataListener);
5055

5156
if (watch) {
5257
await new Promise((resolve) => {
@@ -80,32 +85,32 @@ export default function createReScriptPlugin(config?: Config): Plugin {
8085
let childProcessReScript: undefined | ReScriptProcess;
8186

8287
// Retrieve config
83-
const output = config?.loader?.output ?? './lib/es6';
84-
const suffix = config?.loader?.suffix ?? '.bs.js';
85-
const suffixRegex = new RegExp(`${suffix.replace('.', '\\.')}$`);
88+
const output = config?.loader?.output ?? "./lib/es6";
89+
const suffix = config?.loader?.suffix ?? ".bs.js";
90+
const suffixRegex = new RegExp(`${suffix.replace(".", "\\.")}$`);
8691
const silent = config?.silent ?? false;
87-
const buildArgs = config?.buildArgs ?? '';
92+
const buildArgs = config?.buildArgs ?? "";
8893

8994
return {
90-
name: '@jihchi/vite-plugin-rescript',
91-
enforce: 'pre',
95+
name: "@jihchi/vite-plugin-rescript",
96+
enforce: "pre",
9297
async configResolved(resolvedConfig) {
9398
root = resolvedConfig.root;
9499

95100
const { build, command, inlineConfig } = resolvedConfig;
96101

97102
// exclude "vite preview [--mode <mode>]"
98103
const isOnlyDevServerLaunching =
99-
command === 'serve' && !Object.hasOwn(inlineConfig, 'preview');
104+
command === "serve" && !Object.hasOwn(inlineConfig, "preview");
100105

101-
const isBuildForProduction = command === 'build';
106+
const isBuildForProduction = command === "build";
102107

103108
const needReScript = isOnlyDevServerLaunching || isBuildForProduction;
104109

105110
// The watch command can only be run by one process at the same time.
106-
const isLocked = existsSync(path.resolve('./.bsb.lock'));
111+
const isLocked = existsSync(path.resolve("./.bsb.lock"));
107112

108-
const watch = !isLocked && (command === 'serve' || Boolean(build.watch));
113+
const watch = !isLocked && (command === "serve" || Boolean(build.watch));
109114

110115
if (needReScript) {
111116
childProcessReScript = await launchReScript(watch, silent, buildArgs);
@@ -116,32 +121,32 @@ export default function createReScriptPlugin(config?: Config): Plugin {
116121
// If the build watcher is enabled (adding watch config would automatically enable it),
117122
// exclude rescript files since recompilation should be based on the generated JS files.
118123
watch: userConfig.build?.watch
119-
? { exclude: ['**/*.res', '**/*.resi'] }
124+
? { exclude: ["**/*.res", "**/*.resi"] }
120125
: null,
121126
},
122127
server: {
123128
watch: {
124129
// Ignore rescript files when watching since they may occasionally trigger hot update
125-
ignored: ['**/*.res', '**/*.resi'],
130+
ignored: ["**/*.res", "**/*.resi"],
126131
},
127132
},
128133
}),
129134
configureServer(server) {
130135
// Manually find and parse log file after server start since
131136
// initial compilation does not trigger handleHotUpdate.
132-
fs.readFile(path.resolve('./lib/bs/.compiler.log'), 'utf8').then(
137+
fs.readFile(path.resolve("./lib/bs/.compiler.log"), "utf8").then(
133138
(data) => {
134139
const log = data.toString();
135140
const err = parseCompilerLog(log);
136-
if (err) server.hot.send({ type: 'error', err });
137-
},
141+
if (err) server.hot.send({ type: "error", err });
142+
}
138143
);
139144
},
140145
// Hook that resolves `.bs.js` imports to their `.res` counterpart
141146
async resolveId(source, importer, options) {
142-
if (source.endsWith('.res')) usingLoader = true;
147+
if (source.endsWith(".res")) usingLoader = true;
143148
if (options.isEntry || !importer) return null;
144-
if (!importer.endsWith('.res')) return null;
149+
if (!importer.endsWith(".res")) return null;
145150
if (!source.endsWith(suffix)) return null;
146151
if (path.isAbsolute(source)) return null;
147152

@@ -157,7 +162,7 @@ export default function createReScriptPlugin(config?: Config): Plugin {
157162
}
158163

159164
// Only replace the last occurrence
160-
const resFile = source.replace(suffixRegex, '.res');
165+
const resFile = source.replace(suffixRegex, ".res");
161166
const id = path.join(dirname, resFile);
162167

163168
// Enable other plugins to resolve the file
@@ -177,7 +182,7 @@ export default function createReScriptPlugin(config?: Config): Plugin {
177182
},
178183
// Hook that loads the generated `.bs.js` file from `lib/es6` for ReScript files
179184
async load(id) {
180-
if (!id.endsWith('.res')) return null;
185+
if (!id.endsWith(".res")) return null;
181186

182187
// Find the path to the generated js file
183188
const relativePath = path.relative(root, id);
@@ -189,7 +194,7 @@ export default function createReScriptPlugin(config?: Config): Plugin {
189194
this.addWatchFile(filePath);
190195

191196
// Read the file content and return the code
192-
return { code: await fs.readFile(filePath, 'utf8') };
197+
return { code: await fs.readFile(filePath, "utf8") };
193198
},
194199
async handleHotUpdate({ file, read, server }) {
195200
// HMR is not automatically triggered when using the ReScript file loader.
@@ -198,15 +203,15 @@ export default function createReScriptPlugin(config?: Config): Plugin {
198203
if (usingLoader && file.endsWith(suffix)) {
199204
const lib = path.resolve(output);
200205
const relativePath = path.relative(lib, file);
201-
if (relativePath.startsWith('..')) return;
202-
const resFile = relativePath.replace(suffixRegex, '.res');
206+
if (relativePath.startsWith("..")) return;
207+
const resFile = relativePath.replace(suffixRegex, ".res");
203208
const id = path.join(root, resFile);
204209
const moduleNode = server.moduleGraph.getModuleById(id);
205210
if (moduleNode) return [moduleNode];
206-
} else if (file.endsWith('.compiler.log')) {
211+
} else if (file.endsWith(".compiler.log")) {
207212
const log = await read();
208213
const err = parseCompilerLog(log);
209-
if (err) server.hot.send({ type: 'error', err });
214+
if (err) server.hot.send({ type: "error", err });
210215
}
211216

212217
return;

0 commit comments

Comments
 (0)