Skip to content
Draft
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/babel-caller-platform.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@callstack/repack": minor
---

Pass the target platform and the project's `@babel/runtime` version to Babel through caller data, matching what Metro passes to `@react-native/babel-preset`. With React Native 0.88 and newer, `Platform.OS` and `Platform.select()` are now inlined at build time, which lets the minifier drop code for other platforms. With React Native 0.89 and newer, `babel-loader` also imports all Babel helpers from `@babel/runtime` instead of inlining the newer ones into every file.
77 changes: 77 additions & 0 deletions packages/repack/src/loaders/babelLoader/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { getBabelCaller, getBabelRuntime } from '../utils.js';

function createProject(babelRuntimeVersion?: string) {
const projectRoot = fs.realpathSync(
fs.mkdtempSync(path.join(os.tmpdir(), 'repack-babel-caller-'))
);
if (babelRuntimeVersion) {
const runtimeDir = path.join(projectRoot, 'node_modules/@babel/runtime');
fs.mkdirSync(runtimeDir, { recursive: true });
fs.writeFileSync(
path.join(runtimeDir, 'package.json'),
JSON.stringify({ name: '@babel/runtime', version: babelRuntimeVersion })
);
}
return projectRoot;
}

describe('getBabelRuntime', () => {
it("returns the location and version of the project's @babel/runtime", () => {
const projectRoot = createProject('7.99.0');

expect(getBabelRuntime(projectRoot)).toEqual({
babelRuntimeModuleName: path.join(
projectRoot,
'node_modules/@babel/runtime'
),
enableBabelRuntime: '7.99.0',
});
});
});

describe('getBabelCaller', () => {
const projectRoot = createProject('7.99.0');
const babelRuntime = getBabelRuntime(projectRoot);
const context = path.join(projectRoot, 'src');

it('reads the platform exposed by BabelPlugin', () => {
expect(
getBabelCaller({
context,
rootContext: projectRoot,
repack: { platform: 'ios' },
// the plugin value wins over the compiler name
_compiler: { options: { name: 'android' } },
})
).toEqual({
name: '@callstack/repack',
platform: 'ios',
inlinePlatform: true,
...babelRuntime,
});
});

it('falls back to the compiler name as the platform', () => {
expect(
getBabelCaller({
context,
rootContext: projectRoot,
_compiler: { options: { name: 'android' } },
})
).toMatchObject({ platform: 'android', inlinePlatform: true });
});

it('does not enable platform inlining when the platform is unknown', () => {
// parallel loaders in Rspack get a compiler without most of its options
const caller = getBabelCaller({
context,
rootContext: projectRoot,
_compiler: { options: {} },
});

expect(caller).toEqual({ name: '@callstack/repack', ...babelRuntime });
});
});
3 changes: 2 additions & 1 deletion packages/repack/src/loaders/babelLoader/babelLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type {
CustomTransformOptions,
} from './options.js';
import {
getBabelCaller,
isIgnoredRepackDeepImport,
isTSXSource,
isTypeScriptSource,
Expand Down Expand Up @@ -173,7 +174,7 @@ export default async function babelLoader(
const result = await transform(
source,
{
caller: { name: '@callstack/repack' },
caller: getBabelCaller(this),
filename: this.resourcePath,
sourceMaps: withSourceMaps,
sourceFileName: this.resourcePath,
Expand Down
87 changes: 87 additions & 0 deletions packages/repack/src/loaders/babelLoader/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import fs from 'node:fs';
import path from 'node:path';
import type { ParseResult, TransformOptions } from '@babel/core';
import type { RawSourceMap } from '@rspack/core';
import { importDefaultESM } from '../../helpers/index.js';
Expand Down Expand Up @@ -125,3 +127,88 @@ const IGNORED_REPACK_PATHS_REGEX = new RegExp(
export function isIgnoredRepackDeepImport(filename: string): boolean {
return IGNORED_REPACK_PATHS_REGEX.test(filename);
}

interface BabelCallerSource {
context?: string | null;
rootContext?: string;
/** Custom value set by BabelPlugin through `options.loader`. */
repack?: unknown;
_compiler?: { options?: { name?: string } };
}

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}

function getPlatform(loaderContext: BabelCallerSource): string | undefined {
// set by BabelPlugin through `options.loader`, the only channel that also
// reaches loaders running in Rspack's parallel mode
if (isRecord(loaderContext.repack)) {
const { platform } = loaderContext.repack;
if (typeof platform === 'string') return platform;
}
// without the plugin, fall back to the compiler name used as the platform
return loaderContext._compiler?.options?.name;
}

interface BabelRuntime {
babelRuntimeModuleName: string;
enableBabelRuntime: string;
}

const babelRuntimeCache = new Map<string, BabelRuntime | null>();

/**
* Finds the project's `@babel/runtime` and returns its location and version.
* `@babel/plugin-transform-runtime` assumes version 7.0.0 when it's not told
* otherwise and inlines every newer helper into each file that uses it.
* A version is only safe to target alongside the module it describes,
* so both are returned as a pair.
*/
export function getBabelRuntime(projectRoot: string): BabelRuntime | null {
const cached = babelRuntimeCache.get(projectRoot);
if (cached !== undefined) return cached;

let babelRuntime: BabelRuntime | null = null;
try {
const manifestPath = require.resolve('@babel/runtime/package.json', {
paths: [projectRoot],
});
const manifest: unknown = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
if (isRecord(manifest) && typeof manifest.version === 'string') {
babelRuntime = {
babelRuntimeModuleName: path.dirname(manifestPath),
enableBabelRuntime: manifest.version,
};
}
} catch {
// @babel/runtime is not installed, let the preset use its defaults
}

babelRuntimeCache.set(projectRoot, babelRuntime);
return babelRuntime;
}

/**
* Caller data for Babel, mirroring what Metro passes to
* `@react-native/babel-preset`. Without it the preset falls back to defaults:
* no `Platform.OS` / `Platform.select` inlining and no `@babel/runtime` version.
* Presets that don't read these keys ignore them.
*/
export function getBabelCaller(loaderContext: BabelCallerSource) {
const platform = getPlatform(loaderContext);
// parallel loaders in Rspack had a bug where rootContext
// was the same as context, so we only trust it when they differ
const projectRoot =
loaderContext.rootContext &&
loaderContext.rootContext !== loaderContext.context
? loaderContext.rootContext
: process.cwd();
const babelRuntime = getBabelRuntime(projectRoot);

return {
name: '@callstack/repack',
...(platform ? { platform, inlinePlatform: true } : null),
...babelRuntime,
};
}
13 changes: 10 additions & 3 deletions packages/repack/src/loaders/babelSwcLoader/babelSwcLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import type {
SwcLoaderOptions,
} from '@rspack/core';
import { transform } from '../babelLoader/babelLoader.js';
import { normalizeInputSourceMap } from '../babelLoader/utils.js';
import {
getBabelCaller,
normalizeInputSourceMap,
} from '../babelLoader/utils.js';
import type { BabelSwcLoaderOptions } from './options.js';
import {
addSwcComplementaryTransforms,
Expand Down Expand Up @@ -120,7 +123,7 @@ export default async function babelSwcLoader(

try {
const baseBabelConfig: TransformOptions = {
caller: { name: '@callstack/repack' },
caller: getBabelCaller(this),
root: projectRoot,
filename: this.resourcePath,
sourceMaps: withSourceMaps,
Expand All @@ -142,7 +145,11 @@ export default async function babelSwcLoader(
return;
}

const babelConfig = getProjectBabelConfig(this.resourcePath, projectRoot);
const babelConfig = getProjectBabelConfig(
this.resourcePath,
projectRoot,
baseBabelConfig.caller
);
const detectedBabelTransforms =
babelConfig.plugins?.map((p) => [p.key, p.options] as BabelTransform) ??
[];
Expand Down
10 changes: 7 additions & 3 deletions packages/repack/src/loaders/babelSwcLoader/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { loadOptions } from '@babel/core';
import { loadOptions, type TransformOptions } from '@babel/core';
import type Rspack from '@rspack/core';
import type {
experiments,
Expand All @@ -22,9 +22,13 @@ export function isTSXSource(fileName: string) {
return !!fileName && fileName.endsWith('.tsx');
}

export function getProjectBabelConfig(filename: string, projectRoot?: string) {
export function getProjectBabelConfig(
filename: string,
projectRoot?: string,
caller: TransformOptions['caller'] = { name: '@callstack/repack' }
) {
const babelConfig = loadOptions({
caller: { name: '@callstack/repack' },
caller,
filename,
root: projectRoot,
});
Expand Down
21 changes: 21 additions & 0 deletions packages/repack/src/plugins/BabelPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
import type { Compiler as RspackCompiler } from '@rspack/core';
import type { Compiler as WebpackCompiler } from 'webpack';

export interface BabelPluginConfig {
/** Target application platform, exposed to Re.Pack's Babel loaders. */
platform?: string;
}

/**
* 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.
*
* It also exposes the target platform to Re.Pack's Babel loaders, so they can
* pass it to the Babel preset through caller data.
*
* @category Webpack Plugin
*/
export class BabelPlugin {
constructor(private config: BabelPluginConfig = {}) {}

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

Expand All @@ -22,5 +32,16 @@ export class BabelPlugin {
'babel-loader': [require.resolve('babel-loader')],
},
};

// `options.loader` values are copied onto every loader context, which is
// the only channel that also reaches loaders running in Rspack's parallel
// mode, where the compiler options are not available.
const platform = this.config.platform ?? compiler.options.name;
if (platform) {
compiler.options.loader = {
...compiler.options.loader,
repack: { ...compiler.options.loader?.repack, platform },
};
}
}
}
2 changes: 1 addition & 1 deletion packages/repack/src/plugins/RepackPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export class RepackPlugin {
__DEV__: JSON.stringify(compiler.options.mode === 'development'),
}).apply(compiler);

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

new OutputPlugin({
platform,
Expand Down
30 changes: 30 additions & 0 deletions packages/repack/src/plugins/__tests__/BabelPlugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,34 @@ describe('BabelPlugin', () => {
'babel-loader': [expect.any(String)],
});
});

it('exposes the platform to loaders through options.loader', () => {
compilerMock.options.loader = { existing: true };
new BabelPlugin({ platform: 'ios' }).apply(
compilerMock as unknown as Compiler
);

expect(compilerMock.options.loader).toEqual({
existing: true,
repack: { platform: 'ios' },
});
});

it('falls back to the compiler name as the platform', () => {
const compiler = {
options: { name: 'android' } as Compiler['options'],
};
new BabelPlugin().apply(compiler as unknown as Compiler);

expect(compiler.options.loader).toEqual({
repack: { platform: 'android' },
});
});

it('leaves options.loader untouched when the platform is unknown', () => {
const compiler = { options: {} as Compiler['options'] };
new BabelPlugin().apply(compiler as unknown as Compiler);

expect(compiler.options.loader).toBeUndefined();
});
});
Loading