From ba1856ee9176ae1292c905442ed13d8b6aa11ab4 Mon Sep 17 00:00:00 2001 From: D N <4661784+retyui@users.noreply.github.com> Date: Sat, 26 Sep 2026 09:08:19 +0200 Subject: [PATCH 1/2] feat: No json as string in JS bundle issue: https://github.com/callstack/repack/issues/1461 --- .changeset/raw-json-assets.md | 5 ++ .../getAssetTransformRules.test.ts.snap | 72 +++++++++++++++++++ .../__tests__/getAssetTransformRules.test.ts | 42 +++++++---- .../src/utils/getAssetTransformRules.ts | 18 +++++ .../api/utils/get-asset-transform-rules.md | 12 ++++ 5 files changed, 137 insertions(+), 12 deletions(-) create mode 100644 .changeset/raw-json-assets.md diff --git a/.changeset/raw-json-assets.md b/.changeset/raw-json-assets.md new file mode 100644 index 000000000..bba5b589e --- /dev/null +++ b/.changeset/raw-json-assets.md @@ -0,0 +1,5 @@ +--- +"@callstack/repack": minor +--- + +Add `enableRawJson` option to `getAssetTransformRules`. It is enabled by default and adds a `type: "json"` rule with `generator: { JSONParse: false }`, so `.json` files are bundled as raw text and parsed at runtime with `JSON.parse('...')` instead of being parsed into an object at build time. Pass `enableRawJson: false` to keep the previous behavior. diff --git a/packages/repack/src/utils/__tests__/__snapshots__/getAssetTransformRules.test.ts.snap b/packages/repack/src/utils/__tests__/__snapshots__/getAssetTransformRules.test.ts.snap index c99a6420e..efa357d7c 100644 --- a/packages/repack/src/utils/__tests__/__snapshots__/getAssetTransformRules.test.ts.snap +++ b/packages/repack/src/utils/__tests__/__snapshots__/getAssetTransformRules.test.ts.snap @@ -2,6 +2,13 @@ exports[`getAssetTransformRules should add SVGR rule when svg="svgr" 1`] = ` [ + { + "generator": { + "JSONParse": false, + }, + "test": /\\\\\\.json\\$/, + "type": "json", + }, { "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, "use": { @@ -27,6 +34,13 @@ exports[`getAssetTransformRules should add SVGR rule when svg="svgr" 1`] = ` exports[`getAssetTransformRules should add URI rule when svg="uri" 1`] = ` [ + { + "generator": { + "JSONParse": false, + }, + "test": /\\\\\\.json\\$/, + "type": "json", + }, { "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, "use": { @@ -47,6 +61,13 @@ exports[`getAssetTransformRules should add URI rule when svg="uri" 1`] = ` exports[`getAssetTransformRules should add XML rule when svg="xml" 1`] = ` [ + { + "generator": { + "JSONParse": false, + }, + "test": /\\\\\\.json\\$/, + "type": "json", + }, { "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, "use": { @@ -67,6 +88,13 @@ exports[`getAssetTransformRules should add XML rule when svg="xml" 1`] = ` exports[`getAssetTransformRules should include additional options for SVGR 1`] = ` [ + { + "generator": { + "JSONParse": false, + }, + "test": /\\\\\\.json\\$/, + "type": "json", + }, { "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, "use": { @@ -91,8 +119,31 @@ exports[`getAssetTransformRules should include additional options for SVGR 1`] = ] `; +exports[`getAssetTransformRules should omit the raw JSON rule when enableRawJson is false 1`] = ` +[ + { + "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|svg\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, + "use": { + "loader": "@callstack/repack/assets-loader", + "options": { + "inline": undefined, + "maxInlineSize": undefined, + "remote": undefined, + }, + }, + }, +] +`; + exports[`getAssetTransformRules should return default asset transform rules when no options provided 1`] = ` [ + { + "generator": { + "JSONParse": false, + }, + "test": /\\\\\\.json\\$/, + "type": "json", + }, { "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|svg\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, "use": { @@ -109,6 +160,13 @@ exports[`getAssetTransformRules should return default asset transform rules when exports[`getAssetTransformRules should return rules with inline option when provided 1`] = ` [ + { + "generator": { + "JSONParse": false, + }, + "test": /\\\\\\.json\\$/, + "type": "json", + }, { "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|svg\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, "use": { @@ -125,6 +183,13 @@ exports[`getAssetTransformRules should return rules with inline option when prov exports[`getAssetTransformRules should return rules with maxInlineSize option when provided 1`] = ` [ + { + "generator": { + "JSONParse": false, + }, + "test": /\\\\\\.json\\$/, + "type": "json", + }, { "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|svg\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, "use": { @@ -141,6 +206,13 @@ exports[`getAssetTransformRules should return rules with maxInlineSize option wh exports[`getAssetTransformRules should return rules with remote options when provided 1`] = ` [ + { + "generator": { + "JSONParse": false, + }, + "test": /\\\\\\.json\\$/, + "type": "json", + }, { "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|svg\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, "use": { diff --git a/packages/repack/src/utils/__tests__/getAssetTransformRules.test.ts b/packages/repack/src/utils/__tests__/getAssetTransformRules.test.ts index fe5fa96e9..534e5a8d0 100644 --- a/packages/repack/src/utils/__tests__/getAssetTransformRules.test.ts +++ b/packages/repack/src/utils/__tests__/getAssetTransformRules.test.ts @@ -10,7 +10,7 @@ describe('getAssetTransformRules', () => { const rules = getAssetTransformRules({ inline: true }); // @ts-expect-error - expect(rules[0]?.use?.options?.inline).toEqual(true); + expect(rules[1]?.use?.options?.inline).toEqual(true); expect(rules).toMatchSnapshot(); }); @@ -18,7 +18,7 @@ describe('getAssetTransformRules', () => { const rules = getAssetTransformRules({ maxInlineSize: 1024 }); // @ts-expect-error - expect(rules[0]?.use?.options?.maxInlineSize).toEqual(1024); + expect(rules[1]?.use?.options?.maxInlineSize).toEqual(1024); expect(rules).toMatchSnapshot(); }); @@ -27,39 +27,39 @@ describe('getAssetTransformRules', () => { const rules = getAssetTransformRules({ remote: remoteOptions }); // @ts-expect-error - expect(rules[0]?.use?.options?.remote).toHaveProperty('enabled', true); + expect(rules[1]?.use?.options?.remote).toHaveProperty('enabled', true); expect(rules).toMatchSnapshot(); }); it('should add SVGR rule when svg="svgr"', () => { const rules = getAssetTransformRules({ svg: 'svgr' }); - expect(rules).toHaveLength(2); - expect(rules[1]?.use?.loader).toEqual('@svgr/webpack'); + expect(rules).toHaveLength(3); + expect(rules[2]?.use?.loader).toEqual('@svgr/webpack'); expect(rules).toMatchSnapshot(); }); it('should add XML rule when svg="xml"', () => { const rules = getAssetTransformRules({ svg: 'xml' }); - expect(rules).toHaveLength(2); + expect(rules).toHaveLength(3); // @ts-expect-error - expect(rules[1]?.type).toEqual('asset/source'); + expect(rules[2]?.type).toEqual('asset/source'); expect(rules).toMatchSnapshot(); }); it('should add URI rule when svg="uri"', () => { const rules = getAssetTransformRules({ svg: 'uri' }); - expect(rules).toHaveLength(2); + expect(rules).toHaveLength(3); // @ts-expect-error - expect(rules[1]?.type).toEqual('asset/inline'); + expect(rules[2]?.type).toEqual('asset/inline'); expect(rules).toMatchSnapshot(); }); it('should exclude .svg from main asset extensions when svg option is provided', () => { const rules = getAssetTransformRules({ svg: 'uri' }); - const ruleTest = rules[0]?.test; + const ruleTest = rules[1]?.test; expect(ruleTest.test('test.svg')).toEqual(false); }); @@ -68,8 +68,26 @@ describe('getAssetTransformRules', () => { svg: { type: 'svgr', options: { dimensions: false } }, }); - expect(rules).toHaveLength(2); - expect(rules[1]?.use?.options).toHaveProperty('dimensions', false); + expect(rules).toHaveLength(3); + expect(rules[2]?.use?.options).toHaveProperty('dimensions', false); + expect(rules).toMatchSnapshot(); + }); + + it('should add raw JSON rule by default', () => { + const rules = getAssetTransformRules(); + + expect(rules[0]).toEqual({ + test: /\.json$/, + type: 'json', + generator: { JSONParse: false }, + }); + }); + + it('should omit the raw JSON rule when enableRawJson is false', () => { + const rules = getAssetTransformRules({ enableRawJson: false }); + + expect(rules).toHaveLength(1); + expect(rules[0]?.test.source).not.toContain('json'); expect(rules).toMatchSnapshot(); }); }); diff --git a/packages/repack/src/utils/getAssetTransformRules.ts b/packages/repack/src/utils/getAssetTransformRules.ts index c3040121d..203d0af96 100644 --- a/packages/repack/src/utils/getAssetTransformRules.ts +++ b/packages/repack/src/utils/getAssetTransformRules.ts @@ -58,6 +58,14 @@ interface GetAssetTransformRulesOptions { * - 'uri': Loads SVGs as inline URIs to be used with SvgUri from react-native-svg */ svg?: SvgType; + + /** + * Whether to load `.json` files as raw text instead of parsing them at build time. + * When enabled, JSON files are emitted as a string and parsed at runtime with `JSON.parse('...')`. + * + * @defaultValue true + */ + enableRawJson?: boolean; } /** @@ -68,6 +76,7 @@ interface GetAssetTransformRulesOptions { * @param options.maxInlineSize Maximum asset file size in bytes to inline as base64 URIs (requires inline: true); larger assets are extracted as separate files * @param options.remote Configuration for remote asset loading with publicPath and optional assetPath function * @param options.svg Determines how SVG files should be processed ('svgr', 'xml', or 'uri') + * @param options.enableRawJson Whether to load `.json` files as raw text parsed at runtime with `JSON.parse` (defaults to true) * * @returns Array of webpack/rspack rules for transforming assets */ @@ -76,6 +85,7 @@ export function getAssetTransformRules({ maxInlineSize, remote, svg, + enableRawJson = true, }: GetAssetTransformRulesOptions = {}) { const extensions = svg ? ASSET_EXTENSIONS.filter((ext) => ext !== 'svg') @@ -90,6 +100,14 @@ export function getAssetTransformRules({ const rules = []; + if (enableRawJson) { + rules.push({ + test: /\.json$/, + type: 'json', + generator: { JSONParse: false }, + }); + } + rules.push({ test: getAssetExtensionsRegExp(extensions), use: { diff --git a/website/src/latest/api/utils/get-asset-transform-rules.md b/website/src/latest/api/utils/get-asset-transform-rules.md index 5210df214..17d164688 100644 --- a/website/src/latest/api/utils/get-asset-transform-rules.md +++ b/website/src/latest/api/utils/get-asset-transform-rules.md @@ -22,6 +22,7 @@ interface GetAssetTransformRulesOptions { }) => string; }; svg?: "svgr" | "xml" | "uri" | { type: "svgr", options: Record }; + enableRawJson?: boolean; } ``` @@ -97,6 +98,17 @@ Allows to configure additional options to `@svgr/webpack`. The full list of avai Learn more about using SVG in the [SVG guide](/docs/guides/svg). ::: +### options.enableRawJson + +- Type: `boolean` +- Default: `true` + +Whether to load `.json` files as raw text instead of parsing them at build time. + +When enabled (the default), a rule with `type: "json"` and `generator: { JSONParse: false }` is added, so the bundled JSON is emitted as a string and parsed at runtime with `JSON.parse('...')`. This keeps the bundle smaller for large JSON files, since the parsed object is not inlined into the bundle. + +Set it to `false` to disable the rule and let the bundler parse `.json` files at build time. + ## Example ```js title=rspack.config.cjs From 0bf13e905f2c1d24af3177af13f0778562284aee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Muzyk?= Date: Fri, 20 Nov 2026 11:58:14 +0100 Subject: [PATCH 2/2] fix: code review requested changes and some improvements --- .changeset/json-parse-option.md | 5 ++ .changeset/raw-json-assets.md | 5 -- .../repack/src/plugins/JsonParsePlugin.ts | 62 ++++++++++++++ packages/repack/src/plugins/RepackPlugin.ts | 11 +++ .../plugins/__tests__/JsonParsePlugin.test.ts | 85 +++++++++++++++++++ .../plugins/__tests__/RepackPlugin.test.ts | 51 +++++++++++ packages/repack/src/plugins/index.ts | 1 + .../getAssetTransformRules.test.ts.snap | 72 ---------------- .../__tests__/getAssetTransformRules.test.ts | 42 +++------ .../src/utils/getAssetTransformRules.ts | 18 ---- .../src/plugins/JsonParsePlugin.test.ts | 84 ++++++++++++++++++ website/src/latest/api/plugins/internal.md | 4 + website/src/latest/api/plugins/repack.md | 13 +++ .../api/utils/get-asset-transform-rules.md | 12 --- 14 files changed, 328 insertions(+), 137 deletions(-) create mode 100644 .changeset/json-parse-option.md delete mode 100644 .changeset/raw-json-assets.md create mode 100644 packages/repack/src/plugins/JsonParsePlugin.ts create mode 100644 packages/repack/src/plugins/__tests__/JsonParsePlugin.test.ts create mode 100644 packages/repack/src/plugins/__tests__/RepackPlugin.test.ts create mode 100644 tests/integration/src/plugins/JsonParsePlugin.test.ts diff --git a/.changeset/json-parse-option.md b/.changeset/json-parse-option.md new file mode 100644 index 000000000..05502df97 --- /dev/null +++ b/.changeset/json-parse-option.md @@ -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+. diff --git a/.changeset/raw-json-assets.md b/.changeset/raw-json-assets.md deleted file mode 100644 index bba5b589e..000000000 --- a/.changeset/raw-json-assets.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"@callstack/repack": minor ---- - -Add `enableRawJson` option to `getAssetTransformRules`. It is enabled by default and adds a `type: "json"` rule with `generator: { JSONParse: false }`, so `.json` files are bundled as raw text and parsed at runtime with `JSON.parse('...')` instead of being parsed into an object at build time. Pass `enableRawJson: false` to keep the previous behavior. diff --git a/packages/repack/src/plugins/JsonParsePlugin.ts b/packages/repack/src/plugins/JsonParsePlugin.ts new file mode 100644 index 000000000..03fd1f672 --- /dev/null +++ b/packages/repack/src/plugins/JsonParsePlugin.ts @@ -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 }, + }; + } +} diff --git a/packages/repack/src/plugins/RepackPlugin.ts b/packages/repack/src/plugins/RepackPlugin.ts index 9d6c7db00..e3263c248 100644 --- a/packages/repack/src/plugins/RepackPlugin.ts +++ b/packages/repack/src/plugins/RepackPlugin.ts @@ -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'; @@ -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; } /** @@ -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 }, diff --git a/packages/repack/src/plugins/__tests__/JsonParsePlugin.test.ts b/packages/repack/src/plugins/__tests__/JsonParsePlugin.test.ts new file mode 100644 index 000000000..ed282daff --- /dev/null +++ b/packages/repack/src/plugins/__tests__/JsonParsePlugin.test.ts @@ -0,0 +1,85 @@ +import type { Compiler } from '@rspack/core'; +import { JsonParsePlugin } from '../JsonParsePlugin.js'; + +function createCompiler( + bundler: { rspackVersion: string } | { version: string }, + generator?: Record +) { + 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') + ); + }); +}); diff --git a/packages/repack/src/plugins/__tests__/RepackPlugin.test.ts b/packages/repack/src/plugins/__tests__/RepackPlugin.test.ts new file mode 100644 index 000000000..cfa8f3703 --- /dev/null +++ b/packages/repack/src/plugins/__tests__/RepackPlugin.test.ts @@ -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(); + }); +}); diff --git a/packages/repack/src/plugins/index.ts b/packages/repack/src/plugins/index.ts index a4c866e44..65a3d74ad 100644 --- a/packages/repack/src/plugins/index.ts +++ b/packages/repack/src/plugins/index.ts @@ -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'; diff --git a/packages/repack/src/utils/__tests__/__snapshots__/getAssetTransformRules.test.ts.snap b/packages/repack/src/utils/__tests__/__snapshots__/getAssetTransformRules.test.ts.snap index efa357d7c..c99a6420e 100644 --- a/packages/repack/src/utils/__tests__/__snapshots__/getAssetTransformRules.test.ts.snap +++ b/packages/repack/src/utils/__tests__/__snapshots__/getAssetTransformRules.test.ts.snap @@ -2,13 +2,6 @@ exports[`getAssetTransformRules should add SVGR rule when svg="svgr" 1`] = ` [ - { - "generator": { - "JSONParse": false, - }, - "test": /\\\\\\.json\\$/, - "type": "json", - }, { "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, "use": { @@ -34,13 +27,6 @@ exports[`getAssetTransformRules should add SVGR rule when svg="svgr" 1`] = ` exports[`getAssetTransformRules should add URI rule when svg="uri" 1`] = ` [ - { - "generator": { - "JSONParse": false, - }, - "test": /\\\\\\.json\\$/, - "type": "json", - }, { "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, "use": { @@ -61,13 +47,6 @@ exports[`getAssetTransformRules should add URI rule when svg="uri" 1`] = ` exports[`getAssetTransformRules should add XML rule when svg="xml" 1`] = ` [ - { - "generator": { - "JSONParse": false, - }, - "test": /\\\\\\.json\\$/, - "type": "json", - }, { "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, "use": { @@ -88,13 +67,6 @@ exports[`getAssetTransformRules should add XML rule when svg="xml" 1`] = ` exports[`getAssetTransformRules should include additional options for SVGR 1`] = ` [ - { - "generator": { - "JSONParse": false, - }, - "test": /\\\\\\.json\\$/, - "type": "json", - }, { "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, "use": { @@ -119,31 +91,8 @@ exports[`getAssetTransformRules should include additional options for SVGR 1`] = ] `; -exports[`getAssetTransformRules should omit the raw JSON rule when enableRawJson is false 1`] = ` -[ - { - "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|svg\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, - "use": { - "loader": "@callstack/repack/assets-loader", - "options": { - "inline": undefined, - "maxInlineSize": undefined, - "remote": undefined, - }, - }, - }, -] -`; - exports[`getAssetTransformRules should return default asset transform rules when no options provided 1`] = ` [ - { - "generator": { - "JSONParse": false, - }, - "test": /\\\\\\.json\\$/, - "type": "json", - }, { "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|svg\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, "use": { @@ -160,13 +109,6 @@ exports[`getAssetTransformRules should return default asset transform rules when exports[`getAssetTransformRules should return rules with inline option when provided 1`] = ` [ - { - "generator": { - "JSONParse": false, - }, - "test": /\\\\\\.json\\$/, - "type": "json", - }, { "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|svg\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, "use": { @@ -183,13 +125,6 @@ exports[`getAssetTransformRules should return rules with inline option when prov exports[`getAssetTransformRules should return rules with maxInlineSize option when provided 1`] = ` [ - { - "generator": { - "JSONParse": false, - }, - "test": /\\\\\\.json\\$/, - "type": "json", - }, { "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|svg\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, "use": { @@ -206,13 +141,6 @@ exports[`getAssetTransformRules should return rules with maxInlineSize option wh exports[`getAssetTransformRules should return rules with remote options when provided 1`] = ` [ - { - "generator": { - "JSONParse": false, - }, - "test": /\\\\\\.json\\$/, - "type": "json", - }, { "test": /\\\\\\.\\(bmp\\|gif\\|jpg\\|jpeg\\|png\\|psd\\|svg\\|webp\\|tiff\\|m4v\\|mov\\|mp4\\|mpeg\\|mpg\\|webm\\|aac\\|aiff\\|caf\\|m4a\\|mp3\\|wav\\|html\\|pdf\\|yaml\\|yml\\|otf\\|ttf\\|zip\\|obj\\)\\$/, "use": { diff --git a/packages/repack/src/utils/__tests__/getAssetTransformRules.test.ts b/packages/repack/src/utils/__tests__/getAssetTransformRules.test.ts index 534e5a8d0..fe5fa96e9 100644 --- a/packages/repack/src/utils/__tests__/getAssetTransformRules.test.ts +++ b/packages/repack/src/utils/__tests__/getAssetTransformRules.test.ts @@ -10,7 +10,7 @@ describe('getAssetTransformRules', () => { const rules = getAssetTransformRules({ inline: true }); // @ts-expect-error - expect(rules[1]?.use?.options?.inline).toEqual(true); + expect(rules[0]?.use?.options?.inline).toEqual(true); expect(rules).toMatchSnapshot(); }); @@ -18,7 +18,7 @@ describe('getAssetTransformRules', () => { const rules = getAssetTransformRules({ maxInlineSize: 1024 }); // @ts-expect-error - expect(rules[1]?.use?.options?.maxInlineSize).toEqual(1024); + expect(rules[0]?.use?.options?.maxInlineSize).toEqual(1024); expect(rules).toMatchSnapshot(); }); @@ -27,39 +27,39 @@ describe('getAssetTransformRules', () => { const rules = getAssetTransformRules({ remote: remoteOptions }); // @ts-expect-error - expect(rules[1]?.use?.options?.remote).toHaveProperty('enabled', true); + expect(rules[0]?.use?.options?.remote).toHaveProperty('enabled', true); expect(rules).toMatchSnapshot(); }); it('should add SVGR rule when svg="svgr"', () => { const rules = getAssetTransformRules({ svg: 'svgr' }); - expect(rules).toHaveLength(3); - expect(rules[2]?.use?.loader).toEqual('@svgr/webpack'); + expect(rules).toHaveLength(2); + expect(rules[1]?.use?.loader).toEqual('@svgr/webpack'); expect(rules).toMatchSnapshot(); }); it('should add XML rule when svg="xml"', () => { const rules = getAssetTransformRules({ svg: 'xml' }); - expect(rules).toHaveLength(3); + expect(rules).toHaveLength(2); // @ts-expect-error - expect(rules[2]?.type).toEqual('asset/source'); + expect(rules[1]?.type).toEqual('asset/source'); expect(rules).toMatchSnapshot(); }); it('should add URI rule when svg="uri"', () => { const rules = getAssetTransformRules({ svg: 'uri' }); - expect(rules).toHaveLength(3); + expect(rules).toHaveLength(2); // @ts-expect-error - expect(rules[2]?.type).toEqual('asset/inline'); + expect(rules[1]?.type).toEqual('asset/inline'); expect(rules).toMatchSnapshot(); }); it('should exclude .svg from main asset extensions when svg option is provided', () => { const rules = getAssetTransformRules({ svg: 'uri' }); - const ruleTest = rules[1]?.test; + const ruleTest = rules[0]?.test; expect(ruleTest.test('test.svg')).toEqual(false); }); @@ -68,26 +68,8 @@ describe('getAssetTransformRules', () => { svg: { type: 'svgr', options: { dimensions: false } }, }); - expect(rules).toHaveLength(3); - expect(rules[2]?.use?.options).toHaveProperty('dimensions', false); - expect(rules).toMatchSnapshot(); - }); - - it('should add raw JSON rule by default', () => { - const rules = getAssetTransformRules(); - - expect(rules[0]).toEqual({ - test: /\.json$/, - type: 'json', - generator: { JSONParse: false }, - }); - }); - - it('should omit the raw JSON rule when enableRawJson is false', () => { - const rules = getAssetTransformRules({ enableRawJson: false }); - - expect(rules).toHaveLength(1); - expect(rules[0]?.test.source).not.toContain('json'); + expect(rules).toHaveLength(2); + expect(rules[1]?.use?.options).toHaveProperty('dimensions', false); expect(rules).toMatchSnapshot(); }); }); diff --git a/packages/repack/src/utils/getAssetTransformRules.ts b/packages/repack/src/utils/getAssetTransformRules.ts index 203d0af96..c3040121d 100644 --- a/packages/repack/src/utils/getAssetTransformRules.ts +++ b/packages/repack/src/utils/getAssetTransformRules.ts @@ -58,14 +58,6 @@ interface GetAssetTransformRulesOptions { * - 'uri': Loads SVGs as inline URIs to be used with SvgUri from react-native-svg */ svg?: SvgType; - - /** - * Whether to load `.json` files as raw text instead of parsing them at build time. - * When enabled, JSON files are emitted as a string and parsed at runtime with `JSON.parse('...')`. - * - * @defaultValue true - */ - enableRawJson?: boolean; } /** @@ -76,7 +68,6 @@ interface GetAssetTransformRulesOptions { * @param options.maxInlineSize Maximum asset file size in bytes to inline as base64 URIs (requires inline: true); larger assets are extracted as separate files * @param options.remote Configuration for remote asset loading with publicPath and optional assetPath function * @param options.svg Determines how SVG files should be processed ('svgr', 'xml', or 'uri') - * @param options.enableRawJson Whether to load `.json` files as raw text parsed at runtime with `JSON.parse` (defaults to true) * * @returns Array of webpack/rspack rules for transforming assets */ @@ -85,7 +76,6 @@ export function getAssetTransformRules({ maxInlineSize, remote, svg, - enableRawJson = true, }: GetAssetTransformRulesOptions = {}) { const extensions = svg ? ASSET_EXTENSIONS.filter((ext) => ext !== 'svg') @@ -100,14 +90,6 @@ export function getAssetTransformRules({ const rules = []; - if (enableRawJson) { - rules.push({ - test: /\.json$/, - type: 'json', - generator: { JSONParse: false }, - }); - } - rules.push({ test: getAssetExtensionsRegExp(extensions), use: { diff --git a/tests/integration/src/plugins/JsonParsePlugin.test.ts b/tests/integration/src/plugins/JsonParsePlugin.test.ts new file mode 100644 index 000000000..32930b7f9 --- /dev/null +++ b/tests/integration/src/plugins/JsonParsePlugin.test.ts @@ -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) { + 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('"); + }); +}); diff --git a/website/src/latest/api/plugins/internal.md b/website/src/latest/api/plugins/internal.md index 357dbe87a..a6daa136a 100644 --- a/website/src/latest/api/plugins/internal.md +++ b/website/src/latest/api/plugins/internal.md @@ -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. diff --git a/website/src/latest/api/plugins/repack.md b/website/src/latest/api/plugins/repack.md index 44b30f33a..154c68c19 100644 --- a/website/src/latest/api/plugins/repack.md +++ b/website/src/latest/api/plugins/repack.md @@ -180,3 +180,16 @@ module.exports = { ], }; ``` + +### 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" }); +``` + +Needs Rspack 1.3+ or webpack 5.99+, otherwise it is ignored with a warning. A `JSONParse` value set in your config wins. diff --git a/website/src/latest/api/utils/get-asset-transform-rules.md b/website/src/latest/api/utils/get-asset-transform-rules.md index 17d164688..5210df214 100644 --- a/website/src/latest/api/utils/get-asset-transform-rules.md +++ b/website/src/latest/api/utils/get-asset-transform-rules.md @@ -22,7 +22,6 @@ interface GetAssetTransformRulesOptions { }) => string; }; svg?: "svgr" | "xml" | "uri" | { type: "svgr", options: Record }; - enableRawJson?: boolean; } ``` @@ -98,17 +97,6 @@ Allows to configure additional options to `@svgr/webpack`. The full list of avai Learn more about using SVG in the [SVG guide](/docs/guides/svg). ::: -### options.enableRawJson - -- Type: `boolean` -- Default: `true` - -Whether to load `.json` files as raw text instead of parsing them at build time. - -When enabled (the default), a rule with `type: "json"` and `generator: { JSONParse: false }` is added, so the bundled JSON is emitted as a string and parsed at runtime with `JSON.parse('...')`. This keeps the bundle smaller for large JSON files, since the parsed object is not inlined into the bundle. - -Set it to `false` to disable the rule and let the bundler parse `.json` files at build time. - ## Example ```js title=rspack.config.cjs