diff --git a/.changeset/babel-caller-platform.md b/.changeset/babel-caller-platform.md new file mode 100644 index 000000000..0fc131117 --- /dev/null +++ b/.changeset/babel-caller-platform.md @@ -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. diff --git a/packages/repack/src/loaders/babelLoader/__tests__/utils.test.ts b/packages/repack/src/loaders/babelLoader/__tests__/utils.test.ts new file mode 100644 index 000000000..50b6ad320 --- /dev/null +++ b/packages/repack/src/loaders/babelLoader/__tests__/utils.test.ts @@ -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 }); + }); +}); diff --git a/packages/repack/src/loaders/babelLoader/babelLoader.ts b/packages/repack/src/loaders/babelLoader/babelLoader.ts index 3315e903a..ccad7c61e 100644 --- a/packages/repack/src/loaders/babelLoader/babelLoader.ts +++ b/packages/repack/src/loaders/babelLoader/babelLoader.ts @@ -16,6 +16,7 @@ import type { CustomTransformOptions, } from './options.js'; import { + getBabelCaller, isIgnoredRepackDeepImport, isTSXSource, isTypeScriptSource, @@ -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, diff --git a/packages/repack/src/loaders/babelLoader/utils.ts b/packages/repack/src/loaders/babelLoader/utils.ts index a11472c3e..17abe5bcc 100644 --- a/packages/repack/src/loaders/babelLoader/utils.ts +++ b/packages/repack/src/loaders/babelLoader/utils.ts @@ -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'; @@ -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 { + 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(); + +/** + * 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, + }; +} diff --git a/packages/repack/src/loaders/babelSwcLoader/babelSwcLoader.ts b/packages/repack/src/loaders/babelSwcLoader/babelSwcLoader.ts index f22e6b786..fd357239e 100644 --- a/packages/repack/src/loaders/babelSwcLoader/babelSwcLoader.ts +++ b/packages/repack/src/loaders/babelSwcLoader/babelSwcLoader.ts @@ -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, @@ -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, @@ -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) ?? []; diff --git a/packages/repack/src/loaders/babelSwcLoader/utils.ts b/packages/repack/src/loaders/babelSwcLoader/utils.ts index 6d0fe840b..17145f313 100644 --- a/packages/repack/src/loaders/babelSwcLoader/utils.ts +++ b/packages/repack/src/loaders/babelSwcLoader/utils.ts @@ -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, @@ -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, }); diff --git a/packages/repack/src/plugins/BabelPlugin.ts b/packages/repack/src/plugins/BabelPlugin.ts index 9bc8068ec..86b615865 100644 --- a/packages/repack/src/plugins/BabelPlugin.ts +++ b/packages/repack/src/plugins/BabelPlugin.ts @@ -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; @@ -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 }, + }; + } } } diff --git a/packages/repack/src/plugins/RepackPlugin.ts b/packages/repack/src/plugins/RepackPlugin.ts index 9d6c7db00..5a80ea517 100644 --- a/packages/repack/src/plugins/RepackPlugin.ts +++ b/packages/repack/src/plugins/RepackPlugin.ts @@ -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, diff --git a/packages/repack/src/plugins/__tests__/BabelPlugin.test.ts b/packages/repack/src/plugins/__tests__/BabelPlugin.test.ts index 2f3d6ed68..1a4368515 100644 --- a/packages/repack/src/plugins/__tests__/BabelPlugin.test.ts +++ b/packages/repack/src/plugins/__tests__/BabelPlugin.test.ts @@ -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(); + }); });