Unverified Commit da8d2991 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Fix SWC loader ignore for the server layer when Babel is used (#40939)

Specific logic to handle the file transpilation on the server layer is
implemented in SWC (#40603). When Babel is enabled, that SWC transform
is ignored at the moment. In this PR we add an additional SWC pass after
Babel to handle that.

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent a92a3b6d
...@@ -628,19 +628,39 @@ export default async function getBaseWebpackConfig( ...@@ -628,19 +628,39 @@ export default async function getBaseWebpackConfig(
loggedIgnoredCompilerOptions = true loggedIgnoredCompilerOptions = true
} }
const getBabelOrSwcLoader = () => { const getBabelLoader = () => {
if (useSWCLoader && config?.experimental?.swcTraceProfiling) { return {
loader: require.resolve('./babel/loader/index'),
options: {
configFile: babelConfigFile,
isServer: isNodeServer || isEdgeServer,
distDir,
pagesDir,
cwd: dir,
development: dev,
hasReactRefresh: dev && isClient,
hasJsxRuntime: true,
},
}
}
let swcTraceProfilingInitialized = false
const getSwcLoader = (extraOptions?: any) => {
if (
config?.experimental?.swcTraceProfiling &&
!swcTraceProfilingInitialized
) {
// This will init subscribers once only in a single process lifecycle, // This will init subscribers once only in a single process lifecycle,
// even though it can be called multiple times. // even though it can be called multiple times.
// Subscriber need to be initialized _before_ any actual swc's call (transform, etcs) // Subscriber need to be initialized _before_ any actual swc's call (transform, etcs)
// to collect correct trace spans when they are called. // to collect correct trace spans when they are called.
swcTraceProfilingInitialized = true
require('./swc')?.initCustomTraceSubscriber?.( require('./swc')?.initCustomTraceSubscriber?.(
path.join(distDir, `swc-trace-profile-${Date.now()}.json`) path.join(distDir, `swc-trace-profile-${Date.now()}.json`)
) )
} }
return useSWCLoader return {
? {
loader: 'next-swc-loader', loader: 'next-swc-loader',
options: { options: {
isServer: isNodeServer || isEdgeServer, isServer: isNodeServer || isEdgeServer,
...@@ -653,27 +673,14 @@ export default async function getBaseWebpackConfig( ...@@ -653,27 +673,14 @@ export default async function getBaseWebpackConfig(
supportedBrowsers: config.experimental.browsersListForSwc supportedBrowsers: config.experimental.browsersListForSwc
? supportedBrowsers ? supportedBrowsers
: undefined, : undefined,
swcCacheDir: path.join( swcCacheDir: path.join(dir, config?.distDir ?? '.next', 'cache', 'swc'),
dir, ...extraOptions,
config?.distDir ?? '.next',
'cache',
'swc'
),
}, },
} }
: {
loader: require.resolve('./babel/loader/index'),
options: {
configFile: babelConfigFile,
isServer: isNodeServer || isEdgeServer,
distDir,
pagesDir,
cwd: dir,
development: dev,
hasReactRefresh: dev && isClient,
hasJsxRuntime: true,
},
} }
const getBabelOrSwcLoader = () => {
return useSWCLoader ? getSwcLoader() : getBabelLoader()
} }
const defaultLoaders = { const defaultLoaders = {
...@@ -1613,13 +1620,16 @@ export default async function getBaseWebpackConfig( ...@@ -1613,13 +1620,16 @@ export default async function getBaseWebpackConfig(
{ {
test: codeCondition.test, test: codeCondition.test,
issuerLayer: WEBPACK_LAYERS.server, issuerLayer: WEBPACK_LAYERS.server,
use: { use: useSWCLoader
...defaultLoaders.babel, ? getSwcLoader({ isServerLayer: true })
options: { : // When using Babel, we will have to add the SWC loader
...defaultLoaders.babel.options, // as an additional pass to handle RSC correctly.
isServerLayer: true, // This will cause some performance overhead but
}, // acceptable as Babel will not be recommended.
}, [
getSwcLoader({ isServerLayer: true }),
getBabelLoader(),
],
}, },
] ]
: []), : []),
......
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { renderViaHTTP } from 'next-test-utils'
import path from 'path'
import cheerio from 'cheerio'
describe('with babel', () => {
if ((global as any).isNextDeploy) {
it('should skip next deploy for now', () => {})
return
}
if (process.env.NEXT_TEST_REACT_VERSION === '^17') {
it('should skip for react v17', () => {})
return
}
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: new FileRef(path.join(__dirname, 'with-babel')),
dependencies: {
react: 'experimental',
'react-dom': 'experimental',
},
})
})
afterAll(() => next.destroy())
it('should support babel in app dir', async () => {
const html = await renderViaHTTP(next.url, '/')
const $ = cheerio.load(html)
expect($('h1').text()).toBe('hello')
})
})
export default function Root({ children }) {
return (
<html>
<head>
<title>hello</title>
</head>
<body>{children}</body>
</html>
)
}
'client'
import { useState } from 'react'
export default function Page() {
const state = useState('hello')[0]
return <h1>{state}</h1>
}
module.exports = {
presets: ['next/babel'],
}
module.exports = {
experimental: {
appDir: true,
},
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment