Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -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.

<p>
<a href="https://www.npmjs.com/package/solid-loader"><img src="https://img.shields.io/npm/v/solid-loader?style=flat-square&colorA=564341&colorB=EDED91" alt="npm version" /></a>
Expand Down Expand Up @@ -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
{
Expand All @@ -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.
Expand Down Expand Up @@ -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`
Expand Down
12 changes: 1 addition & 11 deletions playground/rspack.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ export default (
{ mode }: Pick<Configuration, 'mode'>,
): Configuration => {
const dev = mode === 'development';
const test = /\.[mc]?[jt]sx$/i;

return {
context: import.meta.dirname,
Expand All @@ -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 },
Expand Down
38 changes: 37 additions & 1 deletion src/helpers.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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<LoaderContext, 'resourcePath' | 'sourceMap'>,
{
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,
),
};
}
18 changes: 17 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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';
Expand All @@ -39,9 +41,23 @@ const solidLoader: LoaderDefinition<SolidLoaderOptions> = 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<
Expand Down
37 changes: 4 additions & 33 deletions src/refresh.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -15,33 +8,11 @@ export type SolidRefreshLoaderOptions = {
const solidRefreshLoader: LoaderDefinition<SolidRefreshLoaderOptions> =
async function (source, sourceMap): Promise<void> {
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)));
}
Expand Down
84 changes: 54 additions & 30 deletions test/basic/index.test.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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 });
}
});
});
}
Loading