Skip to content

chore: Update babel types and do some light cleanup of babel loader #82486

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 12, 2025
Merged
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
10 changes: 5 additions & 5 deletions packages/next/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -188,11 +188,11 @@
"@taskr/clear": "1.1.0",
"@taskr/esnext": "1.1.0",
"@types/amphtml-validator": "1.0.0",
"@types/babel__code-frame": "7.0.2",
"@types/babel__core": "7.1.12",
"@types/babel__generator": "7.6.2",
"@types/babel__template": "7.4.0",
"@types/babel__traverse": "7.11.0",
"@types/babel__code-frame": "7.0.6",
"@types/babel__core": "7.20.5",
"@types/babel__generator": "7.27.0",
"@types/babel__template": "7.4.4",
"@types/babel__traverse": "7.20.7",
"@types/bytes": "3.1.1",
"@types/ci-info": "2.0.0",
"@types/compression": "0.0.36",
Expand Down
58 changes: 37 additions & 21 deletions packages/next/src/build/babel/loader/get-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,31 @@ import { readFileSync } from 'fs'
import JSON5 from 'next/dist/compiled/json5'

import { createConfigItem, loadOptions } from 'next/dist/compiled/babel/core'
import loadConfig from 'next/dist/compiled/babel/core-lib-config'
import loadFullConfig from 'next/dist/compiled/babel/core-lib-config'

import type { NextBabelLoaderOptions, NextJsLoaderContext } from './types'
import { consumeIterator } from './util'
import {
consumeIterator,
type SourceMap,
type BabelLoaderTransformOptions,
} from './util'
import * as Log from '../../output/log'
import jsx from 'next/dist/compiled/babel/plugin-syntax-jsx'
import { isReactCompilerRequired } from '../../swc'

/**
* An internal (non-exported) type used by babel.
*/
export type ResolvedBabelConfig = {
options: BabelLoaderTransformOptions
passes: BabelPluginPasses
externalDependencies: ReadonlyArray<string>
}

export type BabelPlugin = unknown
export type BabelPluginPassList = ReadonlyArray<BabelPlugin>
export type BabelPluginPasses = ReadonlyArray<BabelPluginPassList>

const nextDistPath =
/(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/

Expand Down Expand Up @@ -275,13 +292,13 @@ function checkCustomBabelConfigDeprecation(
* This config should have no unresolved overrides, presets, etc.
*/
async function getFreshConfig(
this: NextJsLoaderContext,
ctx: NextJsLoaderContext,
cacheCharacteristics: CharacteristicsGermaneToCaching,
loaderOptions: NextBabelLoaderOptions,
target: string,
filename: string,
inputSourceMap?: object | null
) {
inputSourceMap?: SourceMap
): Promise<ResolvedBabelConfig | null> {
const hasReactCompiler = await (async () => {
if (
loaderOptions.reactCompilerPlugins &&
Expand Down Expand Up @@ -314,18 +331,18 @@ async function getFreshConfig(

let { isServer, pagesDir, srcDir, development } = loaderOptions

let options = {
let options: BabelLoaderTransformOptions = {
babelrc: false,
cloneInputAst: false,
filename,
inputSourceMap: inputSourceMap || undefined,
inputSourceMap,

// Ensure that Webpack will get a full absolute path in the sourcemap
// so that it can properly map the module back to its internal cached
// modules.
sourceFileName: filename,
sourceMaps: this.sourceMap,
} as any
sourceMaps: ctx.sourceMap,
}

const baseCaller = {
name: 'next-babel-turbo-loader',
Expand All @@ -334,7 +351,7 @@ async function getFreshConfig(

// Provide plugins with insight into webpack target.
// https://github.com/babel/babel-loader/issues/787
target: target,
target,

// Webpack 5 supports TLA behind a flag. We enable it by default
// for Babel, and then webpack will throw an error if the experimental
Expand Down Expand Up @@ -374,7 +391,7 @@ async function getFreshConfig(
// but allow users to override if they want.
options.sourceMaps =
loaderOptions.sourceMaps === undefined
? this.sourceMap
? ctx.sourceMap
: loaderOptions.sourceMaps

options.plugins = [
Expand Down Expand Up @@ -424,12 +441,12 @@ async function getFreshConfig(
if (!(reason instanceof Error)) {
reason = new Error(reason)
}
this.emitWarning(reason)
ctx.emitWarning(reason)
},
})

const loadedOptions = loadOptions(options)
const config = consumeIterator(loadConfig(loadedOptions))
const config = consumeIterator(loadFullConfig(loadedOptions))

return config
}
Expand All @@ -453,12 +470,11 @@ function getCacheKey(cacheCharacteristics: CharacteristicsGermaneToCaching) {
return fileNameOrExt + flags
}

type BabelConfig = any
const configCache: Map<any, BabelConfig> = new Map()
const configCache: Map<any, ResolvedBabelConfig | null> = new Map()
const configFiles: Set<string> = new Set()

export default async function getConfig(
this: NextJsLoaderContext,
ctx: NextJsLoaderContext,
{
source,
target,
Expand All @@ -470,9 +486,9 @@ export default async function getConfig(
loaderOptions: NextBabelLoaderOptions
target: string
filename: string
inputSourceMap?: object | null
inputSourceMap?: SourceMap | undefined
}
): Promise<BabelConfig> {
): Promise<ResolvedBabelConfig | null> {
const cacheCharacteristics = getCacheCharacteristics(
loaderOptions,
source,
Expand All @@ -482,7 +498,7 @@ export default async function getConfig(

if (loaderOptions.transformMode === 'default' && loaderOptions.configFile) {
// Ensures webpack invalidates the cache for this loader when the config file changes
this.addDependency(loaderOptions.configFile)
ctx.addDependency(loaderOptions.configFile)
}

const cacheKey = getCacheKey(cacheCharacteristics)
Expand Down Expand Up @@ -515,8 +531,8 @@ export default async function getConfig(
)
}

const freshConfig = await getFreshConfig.call(
this,
const freshConfig = await getFreshConfig(
ctx,
cacheCharacteristics,
loaderOptions,
target,
Expand Down
41 changes: 28 additions & 13 deletions packages/next/src/build/babel/loader/index.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,27 @@
import type { Span } from '../../../trace'
import transform from './transform'
import type { NextJsLoaderContext } from './types'
import type { SourceMap } from './util'
import type { webpack } from 'next/dist/compiled/webpack/webpack'

async function nextBabelLoader(
this: NextJsLoaderContext,
ctx: NextJsLoaderContext,
parentTrace: Span,
inputSource: string,
inputSourceMap: object | null | undefined
) {
const filename = this.resourcePath
inputSourceMap: SourceMap | null | undefined
): Promise<[string, SourceMap | null | undefined]> {
const filename = ctx.resourcePath

// Ensure `.d.ts` are not processed.
if (filename.endsWith('.d.ts')) {
return [inputSource, inputSourceMap]
}

const target = this.target
const target = ctx.target
const loaderOptions: any = parentTrace
.traceChild('get-options')
// @ts-ignore TODO: remove ignore once webpack 5 types are used
.traceFn(() => this.getOptions())
.traceFn(() => ctx.getOptions())

if (loaderOptions.exclude && loaderOptions.exclude(filename)) {
return [inputSource, inputSourceMap]
Expand All @@ -29,8 +31,8 @@ async function nextBabelLoader(
const { code: transformedSource, map: outputSourceMap } =
await loaderSpanInner.traceAsyncFn(
async () =>
await transform.call(
this,
await transform(
ctx,
inputSource,
inputSourceMap,
loaderOptions,
Expand All @@ -43,25 +45,38 @@ async function nextBabelLoader(
return [transformedSource, outputSourceMap]
}

const nextBabelLoaderOuter = function nextBabelLoaderOuter(
function nextBabelLoaderOuter(
this: NextJsLoaderContext,
inputSource: string,
inputSourceMap: object | null | undefined
// webpack's source map format is compatible with babel, but the type signature doesn't match
inputSourceMap?: any
) {
const callback = this.async()

const loaderSpan = this.currentTraceSpan.traceChild('next-babel-turbo-loader')
loaderSpan
.traceAsyncFn(() =>
nextBabelLoader.call(this, loaderSpan, inputSource, inputSourceMap)
nextBabelLoader(this, loaderSpan, inputSource, inputSourceMap)
)
.then(
([transformedSource, outputSourceMap]: any) =>
callback?.(null, transformedSource, outputSourceMap || inputSourceMap),
([transformedSource, outputSourceMap]) =>
callback?.(
/* err */ null,
transformedSource,
outputSourceMap ?? inputSourceMap
),
(err) => {
callback?.(err)
}
)
}

// check this type matches `webpack.LoaderDefinitionFunction`, but be careful
// not to publicly rely on the webpack type since the generated typescript
// declarations will be wrong.
const _nextBabelLoaderOuter: webpack.LoaderDefinitionFunction<
{},
NextJsLoaderContext
> = nextBabelLoaderOuter

export default nextBabelLoaderOuter
18 changes: 11 additions & 7 deletions packages/next/src/build/babel/loader/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
*/

import traverse from 'next/dist/compiled/babel/traverse'
import generate from 'next/dist/compiled/babel/generator'
import generate, {
type GeneratorResult,
} from 'next/dist/compiled/babel/generator'
import normalizeFile from 'next/dist/compiled/babel/core-lib-normalize-file'
import normalizeOpts from 'next/dist/compiled/babel/core-lib-normalize-opts'
import loadBlockHoistPlugin from 'next/dist/compiled/babel/core-lib-block-hoist-plugin'
Expand All @@ -13,6 +15,7 @@ import getConfig from './get-config'
import { consumeIterator } from './util'
import type { Span } from '../../../trace'
import type { NextJsLoaderContext } from './types'
import type { SourceMap } from './util'

function getTraversalParams(file: any, pluginPairs: any[]) {
const passPairs = []
Expand Down Expand Up @@ -70,24 +73,25 @@ function transformAst(file: any, babelConfig: any, parentSpan: Span) {
}

export default async function transform(
this: NextJsLoaderContext,
ctx: NextJsLoaderContext,
source: string,
inputSourceMap: object | null | undefined,
inputSourceMap: SourceMap | null | undefined,
loaderOptions: any,
filename: string,
target: string,
parentSpan: Span
) {
): Promise<GeneratorResult> {
const getConfigSpan = parentSpan.traceChild('babel-turbo-get-config')
const babelConfig = await getConfig.call(this, {

const babelConfig = await getConfig(ctx, {
source,
loaderOptions,
inputSourceMap,
inputSourceMap: inputSourceMap ?? undefined,
target,
filename,
})
if (!babelConfig) {
return { code: source, map: inputSourceMap }
return { code: source, map: inputSourceMap ?? null }
}
getConfigSpan.stop()

Expand Down
2 changes: 1 addition & 1 deletion packages/next/src/build/babel/loader/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export type NextBabelLoaderOptionDefaultPresets = NextBabelLoaderBaseOptions & {
transformMode: 'default'
hasJsxRuntime: boolean
hasReactRefresh: boolean
sourceMaps?: any[]
sourceMaps?: boolean | 'inline' | 'both' | null | undefined
overrides: any
configFile: string | undefined
}
Expand Down
18 changes: 18 additions & 0 deletions packages/next/src/build/babel/loader/util.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { TransformOptions } from 'next/dist/compiled/babel/core'

export function consumeIterator(iter: Iterator<any>) {
while (true) {
const { value, done } = iter.next()
Expand All @@ -6,3 +8,19 @@ export function consumeIterator(iter: Iterator<any>) {
}
}
}

/**
* Source map standard format as to revision 3.
*
* `TransformOptions` uses this type, but doesn't export it separately
*/
export type SourceMap = NonNullable<TransformOptions['inputSourceMap']>

/**
* An extension of the normal babel configuration, with extra `babel-loader`-specific fields that transforms can read.
*
* See: https://github.com/babel/babel-loader/blob/main/src/injectCaller.js
*/
export type BabelLoaderTransformOptions = TransformOptions & {
target?: string
}
Comment on lines +12 to +26
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The can't be part of types.d.ts because we get type errors in the generated declarations after next build from trying to access next/dist/compiled/babel/core?

I don't really understand enough about the limitations of generated declaration files.

7 changes: 1 addition & 6 deletions packages/next/src/build/babel/plugins/jsx-pragma.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,7 @@ export default function ({
;[newPath] = path.unshiftContainer('body', mapping)
}

for (const declar of newPath.get('declarations')) {
path.scope.registerBinding(
newPath.node.kind,
declar as NodePath<BabelTypes.Node>
)
}
path.scope.registerDeclaration(newPath)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}

if (!existingBinding) {
Expand Down
15 changes: 6 additions & 9 deletions packages/next/src/build/babel/plugins/react-loadable-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export default function ({
let callExpression = refPath.parentPath

if (
callExpression.isMemberExpression() &&
callExpression?.isMemberExpression() &&
callExpression.node.computed === false
) {
const property = callExpression.get('property')
Expand All @@ -74,14 +74,11 @@ export default function ({
}
}

if (!callExpression.isCallExpression()) return
if (!callExpression?.isCallExpression()) return

const callExpression_ =
callExpression as NodePath<BabelTypes.CallExpression>
Comment on lines -79 to -80
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isCallExpression already provides the appropriate narrowing via a type predicate.


let args = callExpression_.get('arguments')
let args = callExpression.get('arguments')
if (args.length > 2) {
throw callExpression_.buildCodeFrameError(
throw callExpression.buildCodeFrameError(
'next/dynamic only accepts 2 arguments'
)
}
Expand All @@ -97,10 +94,10 @@ export default function ({
options = args[0]
} else {
if (!args[1]) {
callExpression_.node.arguments.push(t.objectExpression([]))
callExpression.node.arguments.push(t.objectExpression([]))
}
// This is needed as the code is modified above
args = callExpression_.get('arguments')
args = callExpression.get('arguments')
loader = args[0]
options = args[1]
}
Expand Down
Loading
Loading