Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/json-parse-option.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@callstack/repack": minor
---

Add `jsonParse` option to `RepackPlugin`. It sets `module.generator.json.JSONParse`, so `jsonParse: false` bundles `.json` files as JS objects instead of `JSON.parse('...')` calls, which is faster in release builds on Hermes. It is off by default and needs Rspack 1.3.0+ or webpack 5.99.0+.
62 changes: 62 additions & 0 deletions packages/repack/src/plugins/JsonParsePlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import type { Compiler as RspackCompiler } from '@rspack/core';
import semver from 'semver';
import type { Compiler as WebpackCompiler } from 'webpack';
import { isRspackCompiler } from '../helpers/index.js';

const MIN_RSPACK_VERSION = '1.3.0';
const MIN_WEBPACK_VERSION = '5.99.0';

function getBundlerSupport(compiler: RspackCompiler) {
const bundler = isRspackCompiler(compiler)
? {
name: 'Rspack',
version: compiler.webpack.rspackVersion,
minVersion: MIN_RSPACK_VERSION,
}
: {
name: 'webpack',
version: (compiler as unknown as WebpackCompiler).webpack.version,
minVersion: MIN_WEBPACK_VERSION,
};

return {
...bundler,
supported: semver.gte(
semver.coerce(bundler.version) ?? '0.0.0',
bundler.minVersion
),
};
}

export class JsonParsePlugin {
constructor(private jsonParse: boolean) {}

apply(compiler: RspackCompiler): void;
apply(compiler: WebpackCompiler): void;

apply(__compiler: unknown) {
const compiler = __compiler as RspackCompiler;
const logger = compiler.getInfrastructureLogger('RepackJsonParsePlugin');

const generator = compiler.options.module.generator ?? {};
const jsonGenerator = generator.json ?? {};

if (jsonGenerator.JSONParse !== undefined) {
return;
}

const bundler = getBundlerSupport(compiler);
if (!bundler.supported) {
logger.warn(
`The jsonParse option needs ${bundler.name} ${bundler.minVersion} or newer ` +
`(found ${bundler.version}). It will be ignored.`
);
return;
}

compiler.options.module.generator = {
...generator,
json: { ...jsonGenerator, JSONParse: this.jsonParse },
};
}
}
11 changes: 11 additions & 0 deletions packages/repack/src/plugins/RepackPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Compiler as RspackCompiler } from '@rspack/core';
import type { Compiler as WebpackCompiler } from 'webpack';
import { BabelPlugin } from './BabelPlugin.js';
import { DevelopmentPlugin } from './DevelopmentPlugin.js';
import { JsonParsePlugin } from './JsonParsePlugin.js';
import { LoggerPlugin, type LoggerPluginConfig } from './LoggerPlugin.js';
import { NativeEntryPlugin } from './NativeEntryPlugin/index.js';
import { OutputPlugin, type OutputPluginConfig } from './OutputPlugin/index.js';
Expand Down Expand Up @@ -42,6 +43,12 @@ export interface RepackPluginConfig {
* Refer to {@link OutputPluginConfig.extraChunks} for more details.
*/
extraChunks?: OutputPluginConfig['extraChunks'];

/**
* Sets `module.generator.json.JSONParse`. `false` bundles `.json` files as JS objects,
* which is faster on Hermes in release builds. Needs Rspack 1.3+ or webpack 5.99+.
*/
jsonParse?: boolean;
}

/**
Expand Down Expand Up @@ -127,6 +134,10 @@ export class RepackPlugin {

new SourceMapPlugin({ platform }).apply(compiler);

if (this.config.jsonParse !== undefined) {
new JsonParsePlugin(this.config.jsonParse).apply(compiler);
}

if (typeof this.config.logger === 'object') {
new LoggerPlugin({
output: { console: true, ...this.config.logger },
Expand Down
85 changes: 85 additions & 0 deletions packages/repack/src/plugins/__tests__/JsonParsePlugin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import type { Compiler } from '@rspack/core';
import { JsonParsePlugin } from '../JsonParsePlugin.js';

function createCompiler(
bundler: { rspackVersion: string } | { version: string },
generator?: Record<string, unknown>
) {
const warn = jest.fn();
const compiler = {
webpack: bundler,
options: { module: { generator } },
getInfrastructureLogger: () => ({ warn }),
};
return { compiler: compiler as unknown as Compiler, warn };
}

describe('JsonParsePlugin', () => {
it('sets JSONParse on Rspack 1.3.0+', () => {
const { compiler, warn } = createCompiler({ rspackVersion: '1.3.0' });

new JsonParsePlugin(false).apply(compiler);

expect(compiler.options.module.generator).toEqual({
json: { JSONParse: false },
});
expect(warn).not.toHaveBeenCalled();
});

it('sets JSONParse on webpack 5.99.0+', () => {
const { compiler } = createCompiler({ version: '5.99.0' });

new JsonParsePlugin(false).apply(compiler);

expect(compiler.options.module.generator).toEqual({
json: { JSONParse: false },
});
});

it('keeps other generator options', () => {
const { compiler } = createCompiler(
{ rspackVersion: '2.0.0' },
{ asset: { dataUrl: {} } }
);

new JsonParsePlugin(false).apply(compiler);

expect(compiler.options.module.generator).toEqual({
asset: { dataUrl: {} },
json: { JSONParse: false },
});
});

it('keeps JSONParse set by the user', () => {
const { compiler } = createCompiler(
{ rspackVersion: '2.0.0' },
{ json: { JSONParse: true } }
);

new JsonParsePlugin(false).apply(compiler);

expect(compiler.options.module.generator).toEqual({
json: { JSONParse: true },
});
});

it('warns and does nothing on Rspack older than 1.3.0', () => {
const { compiler, warn } = createCompiler({ rspackVersion: '1.2.8' });

new JsonParsePlugin(false).apply(compiler);

expect(compiler.options.module.generator).toBeUndefined();
expect(warn).toHaveBeenCalledWith(expect.stringContaining('Rspack 1.3.0'));
});

it('warns and does nothing on webpack older than 5.99.0', () => {
const { compiler, warn } = createCompiler({ version: '5.98.0' });

new JsonParsePlugin(false).apply(compiler);

expect(compiler.options.module.generator).toBeUndefined();
expect(warn).toHaveBeenCalledWith(
expect.stringContaining('webpack 5.99.0')
);
});
});
51 changes: 51 additions & 0 deletions packages/repack/src/plugins/__tests__/RepackPlugin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import type { Compiler } from '@rspack/core';
import { RepackPlugin } from '../RepackPlugin.js';

function mockPlugin() {
return jest.fn().mockImplementation(() => ({ apply() {} }));
}

jest.mock('../BabelPlugin.js', () => ({ BabelPlugin: mockPlugin() }));
jest.mock('../DevelopmentPlugin.js', () => ({
DevelopmentPlugin: mockPlugin(),
}));
jest.mock('../LoggerPlugin.js', () => ({ LoggerPlugin: mockPlugin() }));
jest.mock('../NativeEntryPlugin/index.js', () => ({
NativeEntryPlugin: mockPlugin(),
}));
jest.mock('../OutputPlugin/index.js', () => ({ OutputPlugin: mockPlugin() }));
jest.mock('../RepackTargetPlugin/index.js', () => ({
RepackTargetPlugin: mockPlugin(),
}));
jest.mock('../SourceMapPlugin.js', () => ({ SourceMapPlugin: mockPlugin() }));

function createCompiler() {
return {
webpack: {
rspackVersion: '2.0.0',
DefinePlugin: jest.fn().mockImplementation(() => ({ apply() {} })),
},
options: { name: 'ios', mode: 'production', context: '/', module: {} },
getInfrastructureLogger: () => ({ warn: jest.fn() }),
} as unknown as Compiler;
}

describe('RepackPlugin jsonParse option', () => {
it('sets module.generator.json.JSONParse when jsonParse is set', () => {
const compiler = createCompiler();

new RepackPlugin({ jsonParse: false }).apply(compiler);

expect(compiler.options.module.generator).toEqual({
json: { JSONParse: false },
});
});

it('leaves module.generator untouched when jsonParse is not set', () => {
const compiler = createCompiler();

new RepackPlugin().apply(compiler);

expect(compiler.options.module.generator).toBeUndefined();
});
});
1 change: 1 addition & 0 deletions packages/repack/src/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export * from './BabelPlugin.js';
export * from './CodeSigningPlugin/index.js';
export * from './DevelopmentPlugin.js';
export * from './HermesBytecodePlugin/index.js';
export * from './JsonParsePlugin.js';
export * from './LoggerPlugin.js';
export * from './ManifestPlugin.js';
export * from './ModuleFederationPlugin.js';
Expand Down
84 changes: 84 additions & 0 deletions tests/integration/src/plugins/JsonParsePlugin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { createContext, runInContext } from 'node:vm';
import { plugins } from '@callstack/repack';
import type { Configuration } from '@rspack/core';
import { describe, expect, it } from 'vitest';
import {
compile,
createCompiler,
createVirtualModulePlugin,
} from '../helpers.js';

const data = { greeting: 'Bonjour le monde', items: [1, 2, 3] };

const virtualModules = {
'./index.cjs': `
globalThis.data = require('./data.json');
globalThis.animation = require('./animation.lottie.json');
`,
'./data.json': JSON.stringify(data),
'./animation.lottie.json': JSON.stringify({ layers: ['lottie-layer'] }),
};

async function compileJson(config: Partial<Configuration>) {
const virtualPlugin = await createVirtualModulePlugin(virtualModules);
const compiler = await createCompiler({
context: __dirname,
mode: 'none',
devtool: false,
entry: './index.cjs',
output: { path: '/out', filename: 'main.js', publicPath: '' },
...config,
plugins: [virtualPlugin, ...(config.plugins ?? [])],
} satisfies Configuration);

return compile(compiler);
}

function executeBundle(code: string) {
const context = createContext({});
runInContext(code, context);
return context;
}

describe('JsonParsePlugin', () => {
it('keeps JSON.parse by default', async () => {
const { code } = await compileJson({});

expect(code).toContain("JSON.parse('");
expect(executeBundle(code).data).toEqual(data);
});

it('bundles JSON as JS objects with jsonParse: false', async () => {
const { code } = await compileJson({
plugins: [new plugins.JsonParsePlugin(false)],
});

expect(code).not.toContain('JSON.parse(');
expect(executeBundle(code).data).toEqual(data);
});

it("keeps the user's own .json rules", async () => {
const { code, volume } = await compileJson({
module: {
rules: [{ test: /\.lottie\.json$/, type: 'asset/resource' }],
},
plugins: [new plugins.JsonParsePlugin(false)],
});

expect(code).not.toContain('lottie-layer');
const emitted = Object.keys(volume.toJSON()).filter((file) =>
file.endsWith('.json')
);
expect(emitted).toHaveLength(1);
expect(executeBundle(code).data).toEqual(data);
});

it("keeps the user's own JSONParse setting", async () => {
const { code } = await compileJson({
module: { generator: { json: { JSONParse: true } } },
plugins: [new plugins.JsonParsePlugin(false)],
});

expect(code).toContain("JSON.parse('");
});
});
4 changes: 4 additions & 0 deletions website/src/latest/api/plugins/internal.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ On the React Native 0.87 layout the plugin also prepends resolve aliases: `react

## RepackTargetPlugin

## JsonParsePlugin

Plugin that sets `module.generator.json.JSONParse`. `RepackPlugin` uses it for the [`jsonParse`](/api/plugins/repack#jsonparse) option. It does nothing when `JSONParse` is already set in the config, and prints a warning instead on Rspack older than 1.3.0 or webpack older than 5.99.0.

## BabelPlugin

Plugin that adds `babel-loader` fallback to resolveLoader configuration. This ensures babel-loader can be resolved regardless of the package manager used, as some package managers (like `pnpm`) require loaders to be direct dependencies rather than allowing them to be resolved through nested dependencies.
Expand Down
13 changes: 13 additions & 0 deletions website/src/latest/api/plugins/repack.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,16 @@
],
};
```

### jsonParse

- Type: `boolean`
- Default: `undefined`

Sets [`module.generator.json.JSONParse`](https://rspack.rs/config/module-generator). With `false`, `.json` files are bundled as JS objects instead of `JSON.parse('...')` calls. This makes `require` of large JSON faster on Hermes in release builds, but makes gzipped bundles bigger, JSON load slower in development and `hermesc` use more memory. Best used for production only:

```js
new Repack.RepackPlugin({ jsonParse: mode !== "production" });
```

Check failure on line 193 in website/src/latest/api/plugins/repack.md

View check run for this annotation

apex-sentinel-staging / Apex Sentinel

major: Docs example inverts jsonParse: it enables the JS-object output in dev, not production

The snippet `jsonParse: mode !== "production"` enables JS-object bundling in development and disables it in production — the opposite of what the surrounding prose recommends ("Best used for production only"). `jsonParse: false` is the value that bundles `.json` as JS objects, so `!==` is inverted; users who copy this pay the cost (bigger bundles, slower load, more `hermesc` memory) in dev and get none of the benefit in release builds.
Comment thread
MrMuzyk marked this conversation as resolved.
Resolved

Needs Rspack 1.3+ or webpack 5.99+, otherwise it is ignored with a warning. A `JSONParse` value set in your config wins.
Loading