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/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/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.