diff --git a/README.md b/README.md
index 18811c8..10757ae 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# solid-loader
-A Rspack 2 loader for Solid 2 JSX and TSX. It uses Solid’s native compiler by default and includes a separate loader for hot module replacement (HMR) with Solid Refresh.
+A Rspack 2 loader for Solid 2 JSX and TSX. It uses Solid’s native compiler by default and supports hot module replacement (HMR) with Solid Refresh.
@@ -48,7 +48,11 @@ For TypeScript projects, set `jsx` to `"preserve"` and `jsxImportSource` to `"@s
## Solid Refresh
-To enable Solid Refresh during browser development, turn on HMR, add `'development'` to `resolve.conditionNames` alongside `'solid'`, and include the following rule. Setting `enforce: 'pre'` lets the refresh loader register components before Solid compiles the JSX.
+Solid Refresh runs automatically for browser development builds when Rspack enables HMR. Keep `'solid'` and `'development'` in your development resolve conditions so Solid uses its development runtime. See the [playground configuration](./playground/rspack.config.ts) for a complete example.
+
+### Using a separate pre-loader
+
+If another loader needs to run between Solid Refresh and JSX compilation, use `solid-loader/refresh` as a pre-loader and set `refresh: false` on the main loader. Integrations such as Rsbuild can then register components before a custom Babel transform runs.
```js
{
@@ -62,8 +66,6 @@ To enable Solid Refresh during browser development, turn on HMR, add `'developme
}
```
-See the [playground configuration](./playground/rspack.config.ts) for an example that enables Solid Refresh only in development.
-
## Server-side rendering
If the client will hydrate server-rendered HTML, enable `hydratable` in both builds. Set `solid.generate` to match the output each build needs.
@@ -105,6 +107,13 @@ For typed configurations, import `SolidLoaderOptions`, `SolidCompiler`, or `Soli
Selects the Solid JSX compiler. The default uses `@solidjs/compiler`. Set this to `'babel'` to compile with `@solidjs/babel-plugin`.
+### refresh
+
+- **Type:** `boolean`
+- **Default:** Enabled in development mode when HMR is active, the target supports the DOM, and `solid.generate` is not `'ssr'`.
+
+Runs Solid Refresh before JSX compilation with either compiler. Set `false` to disable the built-in transform or `true` to enable it explicitly. Files in `node_modules` skip the Refresh transform and still go through JSX compilation.
+
### solid
- **Type:** `SolidPresetOptions`
diff --git a/playground/rspack.config.ts b/playground/rspack.config.ts
index a56def8..af4450a 100644
--- a/playground/rspack.config.ts
+++ b/playground/rspack.config.ts
@@ -5,7 +5,6 @@ export default (
{ mode }: Pick,
): Configuration => {
const dev = mode === 'development';
- const test = /\.[mc]?[jt]sx$/i;
return {
context: import.meta.dirname,
@@ -18,21 +17,12 @@ export default (
module: {
rules: [
{
- test,
+ test: /\.[mc]?[jt]sx$/i,
use: [
{ loader: 'builtin:swc-loader', options: { detectSyntax: 'auto' } },
'solid-loader',
],
},
- dev && {
- test,
- enforce: 'pre',
- exclude: /node_modules/,
- dependency: { not: 'url' },
- resourceQuery: { not: /[?&]raw(?:&|=|$)/ },
- with: { type: { not: 'text' } },
- loader: 'solid-loader/refresh',
- },
{
descriptionData: { name: /^@solidjs\/web$/ },
parser: { importDynamic: false },
diff --git a/src/helpers.ts b/src/helpers.ts
index 96eac66..0e257c6 100644
--- a/src/helpers.ts
+++ b/src/helpers.ts
@@ -1,4 +1,4 @@
-import type { RawSourceMap } from '@rspack/core';
+import type { LoaderContext, RawSourceMap } from '@rspack/core';
import remapping from '@jridgewell/remapping';
const DEFAULT_SOLID_SCRIPT_REGEX = /\.(?:jsx|tsx)$/i;
@@ -36,3 +36,39 @@ export const mergeSourceMaps = (
() => null,
) as RawSourceMap;
};
+
+const NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/;
+
+export async function applyRefresh(
+ source: string,
+ sourceMap: RawSourceMap | string | undefined,
+ context: Pick,
+ {
+ filename = context.resourcePath,
+ granular,
+ }: { filename?: string; granular?: boolean } = {},
+) {
+ if (NODE_MODULES_REGEX.test(context.resourcePath)) {
+ return { code: source, map: sourceMap };
+ }
+
+ const { transformRefreshAsync } = await import('@solidjs/compiler');
+ const result = await transformRefreshAsync(source, {
+ filename: getTransformFilename(filename),
+ bundler: 'standard',
+ fixRender: true,
+ ...(typeof granular === 'boolean' ? { granular } : {}),
+ jsx: false,
+ importSource: 'solid-js/refresh',
+ sourceMap: context.sourceMap || Boolean(sourceMap),
+ });
+
+ return {
+ code: result.code,
+ map: mergeSourceMaps(
+ normalizeSourceMap(sourceMap),
+ result.map,
+ context.resourcePath,
+ ),
+ };
+}
diff --git a/src/index.ts b/src/index.ts
index e7c8ccd..96c4f85 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -3,6 +3,7 @@ import type { TransformOptions } from '@babel/core';
import type { LoaderDefinition } from '@rspack/core';
import type { TransformOptions as NativeTransformOptions } from '@solidjs/compiler';
import {
+ applyRefresh,
getTransformFilename,
mergeSourceMaps,
normalizeSourceMap,
@@ -16,6 +17,7 @@ const TSX_REGEX = /\.tsx$/i;
export type SolidLoaderOptions = {
compiler?: SolidCompiler;
+ refresh?: boolean;
solid?: SolidPresetOptions;
scriptRegex?: RegExp;
decoratorVersion?: 'legacy' | '2022-03' | '2023-11';
@@ -39,9 +41,23 @@ const solidLoader: LoaderDefinition = async function (
const filename = getTransformFilename(resourceFilename);
const { compiler = 'native', decoratorVersion } = options;
const solid = { dev: this.mode === 'development', ...options.solid };
- const inputSourceMap = normalizeSourceMap(sourceMap);
+ const refresh =
+ options.refresh ??
+ (this.mode === 'development' &&
+ this.hot &&
+ this.environment.document &&
+ solid.generate !== 'ssr');
try {
+ if (refresh) {
+ const result = await applyRefresh(source, sourceMap, this, {
+ filename: resourceFilename,
+ });
+ source = result.code;
+ sourceMap = result.map;
+ }
+ const inputSourceMap = normalizeSourceMap(sourceMap);
+
if (compiler === 'babel') {
const { transformAsync } = await import('@babel/core');
const parserPlugins: NonNullable<
diff --git a/src/refresh.ts b/src/refresh.ts
index 0379cab..524373e 100644
--- a/src/refresh.ts
+++ b/src/refresh.ts
@@ -1,12 +1,5 @@
-import { transformRefreshAsync } from '@solidjs/compiler';
import type { LoaderDefinition } from '@rspack/core';
-import {
- getTransformFilename,
- mergeSourceMaps,
- normalizeSourceMap,
-} from './helpers.js';
-
-const NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/;
+import { applyRefresh } from './helpers.js';
export type SolidRefreshLoaderOptions = {
granular?: boolean;
@@ -15,33 +8,11 @@ export type SolidRefreshLoaderOptions = {
const solidRefreshLoader: LoaderDefinition =
async function (source, sourceMap): Promise {
const callback = this.async();
- const { granular } = this.getOptions();
-
- if (NODE_MODULES_REGEX.test(this.resourcePath)) {
- callback(null, source, sourceMap);
- return;
- }
try {
- const result = await transformRefreshAsync(source, {
- filename: getTransformFilename(this.resourcePath),
- bundler: 'standard',
- fixRender: true,
- ...(typeof granular === 'boolean' ? { granular } : {}),
- jsx: false,
- importSource: 'solid-js/refresh',
- sourceMap: this.sourceMap || Boolean(sourceMap),
- });
-
- callback(
- null,
- result.code,
- mergeSourceMaps(
- normalizeSourceMap(sourceMap),
- result.map,
- this.resourcePath,
- ),
- );
+ const { granular } = this.getOptions();
+ const result = await applyRefresh(source, sourceMap, this, { granular });
+ callback(null, result.code, result.map);
} catch (error) {
callback(error instanceof Error ? error : new Error(String(error)));
}
diff --git a/test/basic/index.test.ts b/test/basic/index.test.ts
index 37abd1b..db73a77 100644
--- a/test/basic/index.test.ts
+++ b/test/basic/index.test.ts
@@ -1,7 +1,7 @@
import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import path from 'node:path';
-import { rspack } from '@rspack/core';
+import { type RuleSetRule, rspack } from '@rspack/core';
import { RspackDevServer } from '@rspack/dev-server';
import { expect, test } from '@rstest/playwright';
import { getRandomPort } from '@rstackjs/test-utils';
@@ -75,35 +75,59 @@ for (const compiler of ['native', 'babel']) {
});
}
-test('updates a component and preserves its parent state', async ({ page }) => {
- const cwd = await mkdtemp(path.join(playground, 'test-temp-'));
- try {
- await cp(path.join(playground, 'src'), path.join(cwd, 'src'), {
- recursive: true,
- });
- const port = await getRandomPort();
- const compiler = rspack({
- ...playgroundConfig({}, { mode: 'development' }),
- context: cwd,
- });
- const server = new RspackDevServer(
- { host: '127.0.0.1', port, hot: true },
- compiler,
- );
- await server.start();
+for (const mode of [
+ 'automatic refresh',
+ 'explicit Babel refresh',
+ 'pre-loader',
+]) {
+ test(`preserves parent state during HMR with ${mode}`, async ({ page }) => {
+ const cwd = await mkdtemp(path.join(playground, 'test-temp-'));
try {
- await page.goto(`http://127.0.0.1:${port}`);
- const button = page.getByRole('button');
- await button.click();
- await expect(button).toHaveText('Count: 1');
- const file = path.join(cwd, 'src/Counter.tsx');
- const source = await readFile(file, 'utf8');
- await writeFile(file, source.replace('Count:', 'Updated:'));
- await expect(button).toHaveText('Updated: 1');
+ await cp(path.join(playground, 'src'), path.join(cwd, 'src'), {
+ recursive: true,
+ });
+ const port = await getRandomPort();
+ const config = playgroundConfig({}, { mode: 'development' });
+ config.context = cwd;
+ if (mode !== 'automatic refresh') {
+ const rules = config.module!.rules!;
+ const jsxRule = rules[0] as RuleSetRule;
+ const standalone = mode === 'pre-loader';
+ jsxRule.use = [
+ { loader: 'builtin:swc-loader', options: { detectSyntax: 'auto' } },
+ {
+ loader: 'solid-loader',
+ options: { compiler: 'babel', refresh: !standalone },
+ },
+ ];
+ if (standalone) {
+ rules.unshift({
+ test: jsxRule.test,
+ enforce: 'pre',
+ loader: 'solid-loader/refresh',
+ });
+ }
+ }
+ const compiler = rspack(config);
+ const server = new RspackDevServer(
+ { host: '127.0.0.1', port, hot: true },
+ compiler,
+ );
+ await server.start();
+ try {
+ await page.goto(`http://127.0.0.1:${port}`);
+ const button = page.getByRole('button');
+ await button.click();
+ await expect(button).toHaveText('Count: 1');
+ const file = path.join(cwd, 'src/Counter.tsx');
+ const source = await readFile(file, 'utf8');
+ await writeFile(file, source.replace('Count:', 'Updated:'));
+ await expect(button).toHaveText('Updated: 1');
+ } finally {
+ await server.stop();
+ }
} finally {
- await server.stop();
+ await rm(cwd, { recursive: true, force: true });
}
- } finally {
- await rm(cwd, { recursive: true, force: true });
- }
-});
+ });
+}