Skip to content

Commit

Permalink
Ensure React Compiler only runs on first-party browser code (#65851)
Browse files Browse the repository at this point in the history
- Ensure React Compiler runs on first-party code in Turbopack (Excludes
node_modules, but also fully skips running Babel on node_modules)
- Ensure React Compiler runs on first-party code in Webpack (Excludes
node_modules, but also fully skips running Babel on node_modules)
- Ensure React Compiler only runs on browser code -- Per React team
recommendation, it only optimizes browser-facing code currently.
- Ensure React Compiler runs on Pages Router in Webpack -- Was already
the case for Turbopack.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
  • Loading branch information
timneutkens authored May 16, 2024
1 parent 84014c2 commit fc0778b
Show file tree
Hide file tree
Showing 9 changed files with 127 additions and 64 deletions.
28 changes: 25 additions & 3 deletions packages/next/src/build/babel/loader/get-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,28 @@ function getFreshConfig(
filename: string,
inputSourceMap?: object | null
) {
const hasReactCompiler = (() => {
if (
loaderOptions.reactCompilerPlugins &&
loaderOptions.reactCompilerPlugins.length === 0
) {
return false
}

if (
loaderOptions.reactCompilerExclude &&
loaderOptions.reactCompilerExclude(filename)
) {
return false
}

return true
})()

const reactCompilerPluginsIfEnabled = hasReactCompiler
? loaderOptions.reactCompilerPlugins ?? []
: []

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

let options = {
Expand Down Expand Up @@ -304,7 +326,7 @@ function getFreshConfig(
if (loaderOptions.transformMode === 'standalone') {
options.plugins = [
'@babel/plugin-syntax-jsx',
...(loaderOptions.plugins ?? []),
...reactCompilerPluginsIfEnabled,
]
options.presets = [
[
Expand All @@ -314,7 +336,7 @@ function getFreshConfig(
]
options.caller = baseCaller
} else {
let { configFile, plugins, hasJsxRuntime } = loaderOptions
let { configFile, hasJsxRuntime } = loaderOptions
let customConfig: any = configFile
? getCustomBabelConfig(configFile)
: undefined
Expand All @@ -330,7 +352,7 @@ function getFreshConfig(

options.plugins = [
...getPlugins(loaderOptions, cacheCharacteristics),
...(plugins || []),
...reactCompilerPluginsIfEnabled,
...(customConfig?.plugins || []),
]

Expand Down
6 changes: 5 additions & 1 deletion packages/next/src/build/babel/loader/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@ async function nextBabelLoader(
) {
const filename = this.resourcePath
const target = this.target
const loaderOptions = parentTrace
const loaderOptions: any = parentTrace
.traceChild('get-options')
// @ts-ignore TODO: remove ignore once webpack 5 types are used
.traceFn(() => this.getOptions())

if (loaderOptions.exclude && loaderOptions.exclude(filename)) {
return [inputSource, inputSourceMap]
}

const loaderSpanInner = parentTrace.traceChild('next-babel-turbo-transform')
const { code: transformedSource, map: outputSourceMap } =
loaderSpanInner.traceFn(() =>
Expand Down
3 changes: 2 additions & 1 deletion packages/next/src/build/babel/loader/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ export interface NextBabelLoaderBaseOptions {
development: boolean

// Custom plugins to be added to the generated babel options.
plugins?: Array<any>
reactCompilerPlugins?: Array<any>
reactCompilerExclude?: (excludePath: string) => boolean
}

/**
Expand Down
32 changes: 24 additions & 8 deletions packages/next/src/build/get-babel-loader-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import type { ReactCompilerOptions } from '../server/config-shared'

const getReactCompilerPlugins = (
options: boolean | ReactCompilerOptions | undefined,
isDev: boolean
isDev: boolean,
isServer: boolean
) => {
if (!options) {
if (!options || isServer) {
return undefined
}

Expand Down Expand Up @@ -34,7 +35,8 @@ const getBabelLoader = (
srcDir: string,
dev: boolean,
isClient: boolean,
reactCompilerOptions: boolean | ReactCompilerOptions | undefined
reactCompilerOptions: boolean | ReactCompilerOptions | undefined,
reactCompilerExclude: ((excludePath: string) => boolean) | undefined
) => {
if (!useSWCLoader) {
return {
Expand All @@ -50,7 +52,12 @@ const getBabelLoader = (
development: dev,
hasReactRefresh: dev && isClient,
hasJsxRuntime: true,
plugins: getReactCompilerPlugins(reactCompilerOptions, dev),
reactCompilerPlugins: getReactCompilerPlugins(
reactCompilerOptions,
dev,
isServer
),
reactCompilerExclude,
},
}
}
Expand All @@ -67,20 +74,29 @@ const getBabelLoader = (
const getReactCompilerLoader = (
options: boolean | ReactCompilerOptions | undefined,
cwd: string,
isDev: boolean
isDev: boolean,
isServer: boolean,
reactCompilerExclude: ((excludePath: string) => boolean) | undefined
) => {
if (!options) {
const reactCompilerPlugins = getReactCompilerPlugins(options, isDev, isServer)
if (!reactCompilerPlugins) {
return undefined
}

return {
const config: any = {
loader: require.resolve('./babel/loader/index'),
options: {
transformMode: 'standalone',
cwd,
plugins: getReactCompilerPlugins(options, isDev),
reactCompilerPlugins,
},
}

if (reactCompilerExclude) {
config.options.reactCompilerExclude = reactCompilerExclude
}

return config
}

export { getBabelLoader, getReactCompilerLoader }
20 changes: 12 additions & 8 deletions packages/next/src/build/swc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1170,14 +1170,18 @@ function bindingToApi(

for (const key of ['*.ts', '*.js', '*.jsx', '*.tsx']) {
nextConfig.experimental.turbo.rules[key] = {
foreign: false,
loaders: [
getReactCompilerLoader(
originalNextConfig.experimental.reactCompiler,
projectPath,
nextConfig.dev
),
],
browser: {
foreign: false,
loaders: [
getReactCompilerLoader(
originalNextConfig.experimental.reactCompiler,
projectPath,
nextConfig.dev,
false,
undefined
),
],
},
}
}
}
Expand Down
63 changes: 37 additions & 26 deletions packages/next/src/build/webpack-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,29 @@ export default async function getBaseWebpackConfig(
loggedIgnoredCompilerOptions = true
}

const shouldIncludeExternalDirs =
config.experimental.externalDir || !!config.transpilePackages
const codeCondition = {
test: { or: [/\.(tsx|ts|js|cjs|mjs|jsx)$/, /__barrel_optimize__/] },
...(shouldIncludeExternalDirs
? // Allowing importing TS/TSX files from outside of the root dir.
{}
: { include: [dir, ...babelIncludeRegexes] }),
exclude: (excludePath: string) => {
if (babelIncludeRegexes.some((r) => r.test(excludePath))) {
return false
}

const shouldBeBundled = isResourceInPackages(
excludePath,
finalTranspilePackages
)
if (shouldBeBundled) return false

return excludePath.includes('node_modules')
},
}

const babelLoader = getBabelLoader(
useSWCLoader,
babelConfigFile,
Expand All @@ -420,12 +443,19 @@ export default async function getBaseWebpackConfig(
(appDir || pagesDir)!,
dev,
isClient,
config.experimental?.reactCompiler
config.experimental?.reactCompiler,
codeCondition.exclude
)

const reactCompilerLoader = babelLoader
? undefined
: getReactCompilerLoader(config.experimental?.reactCompiler, dir, dev)
: getReactCompilerLoader(
config.experimental?.reactCompiler,
dir,
dev,
isNodeOrEdgeCompilation,
codeCondition.exclude
)

let swcTraceProfilingInitialized = false
const getSwcLoader = (extraOptions: Partial<SWCLoaderOptions>) => {
Expand Down Expand Up @@ -819,30 +849,7 @@ export default async function getBaseWebpackConfig(
dir,
})

const shouldIncludeExternalDirs =
config.experimental.externalDir || !!config.transpilePackages

const pageExtensionsRegex = new RegExp(`\\.(${pageExtensions.join('|')})$`)
const codeCondition = {
test: { or: [/\.(tsx|ts|js|cjs|mjs|jsx)$/, /__barrel_optimize__/] },
...(shouldIncludeExternalDirs
? // Allowing importing TS/TSX files from outside of the root dir.
{}
: { include: [dir, ...babelIncludeRegexes] }),
exclude: (excludePath: string) => {
if (babelIncludeRegexes.some((r) => r.test(excludePath))) {
return false
}

const shouldBeBundled = isResourceInPackages(
excludePath,
finalTranspilePackages
)
if (shouldBeBundled) return false

return excludePath.includes('node_modules')
},
}

const aliasCodeConditionTest = [codeCondition.test, pageExtensionsRegex]

Expand Down Expand Up @@ -1512,7 +1519,11 @@ export default async function getBaseWebpackConfig(
: []),
{
...codeCondition,
use: [...reactRefreshLoaders, defaultLoaders.babel],
use: [
...reactRefreshLoaders,
defaultLoaders.babel,
reactCompilerLoader,
].filter(Boolean),
},
],
},
Expand Down
2 changes: 0 additions & 2 deletions test/e2e/react-compiler/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
'use client'

export default function RootLayout({
children,
}: {
Expand Down
24 changes: 13 additions & 11 deletions test/e2e/react-compiler/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
'use client'

export default function Page() {
let heading: any = null
// eslint-disable-next-line no-eval
const $_ = eval('$')
if (Array.isArray($_)) {
// console.log("useMemoCache", $_);
heading = (
<h1 className="text-9xl">
{/* @ts-ignore */}
React compiler is enabled with <strong>{$_.length}</strong> memo slots
</h1>
)
let heading: any = ''
if (typeof window !== 'undefined') {
// eslint-disable-next-line no-eval
const $_ = eval('$')

if (Array.isArray($_)) {
heading = (
<h1 id="react-compiler-enabled-message">
{/* @ts-ignore */}
React compiler is enabled with <strong>{$_.length}</strong> memo slots
</h1>
)
}
}

return (
Expand Down
13 changes: 9 additions & 4 deletions test/e2e/react-compiler/react-compiler.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { nextTestSetup, FileRef } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { join } from 'path'

describe.each(
Expand All @@ -19,9 +20,13 @@ describe.each(
})

it('should render', async () => {
const $ = await next.render$('/')
expect($('h1').text()).toMatch(
/React compiler is enabled with .+ memo slots/
)
const browser = await next.browser('/')

await retry(async () => {
const text = await browser
.elementByCss('#react-compiler-enabled-message')
.text()
expect(text).toMatch(/React compiler is enabled with \d+ memo slots/)
})
})
})

0 comments on commit fc0778b

Please sign in to comment.