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

Adjust API route loader (#46726

Similar to #46328 but with `hasServerComponents: false` for the compiler
so RSC syntax constrains don't apply here.

Note that since we don’t bundle external modules in API routes, we can't
resolve to `react-server` so that one will be tricky.

Fixes NEXT-625

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/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`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
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`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 33827ede
...@@ -89,6 +89,18 @@ const reactPackagesRegex = /^(react(?:$|\/)|react-dom(?:$|\/))/ ...@@ -89,6 +89,18 @@ const reactPackagesRegex = /^(react(?:$|\/)|react-dom(?:$|\/))/
const staticGenerationAsyncStorageRegex = const staticGenerationAsyncStorageRegex =
/next[\\/]dist[\\/]client[\\/]components[\\/]static-generation-async-storage/ /next[\\/]dist[\\/]client[\\/]components[\\/]static-generation-async-storage/
const mainFieldsPerCompiler: Record<CompilerNameValues, string[]> = {
[COMPILER_NAMES.server]: ['main', 'module'],
[COMPILER_NAMES.client]: ['browser', 'module', 'main'],
[COMPILER_NAMES.edgeServer]: [
'edge-light',
'worker',
'browser',
'module',
'main',
],
}
const BABEL_CONFIG_FILES = [ const BABEL_CONFIG_FILES = [
'.babelrc', '.babelrc',
'.babelrc.json', '.babelrc.json',
...@@ -780,7 +792,7 @@ export default async function getBaseWebpackConfig( ...@@ -780,7 +792,7 @@ export default async function getBaseWebpackConfig(
babel: useSWCLoader ? getSwcLoader() : getBabelLoader(), babel: useSWCLoader ? getSwcLoader() : getBabelLoader(),
} }
const swcLoaderForRSC = hasServerComponents const swcLoaderForServerLayer = hasServerComponents
? useSWCLoader ? useSWCLoader
? getSwcLoader({ isServerLayer: true }) ? getSwcLoader({ isServerLayer: true })
: // When using Babel, we will have to add the SWC loader : // When using Babel, we will have to add the SWC loader
...@@ -790,6 +802,20 @@ export default async function getBaseWebpackConfig( ...@@ -790,6 +802,20 @@ export default async function getBaseWebpackConfig(
[getSwcLoader({ isServerLayer: true }), getBabelLoader()] [getSwcLoader({ isServerLayer: true }), getBabelLoader()]
: [] : []
// Loader for API routes needs to be differently configured as it shouldn't
// have RSC transpiler enabled, so syntax checks such as invalid imports won't
// be performed.
const loaderForAPIRoutes =
hasServerComponents && useSWCLoader
? {
loader: 'next-swc-loader',
options: {
...getSwcLoader().options,
hasServerComponents: false,
},
}
: defaultLoaders.babel
const pageExtensions = config.pageExtensions const pageExtensions = config.pageExtensions
const outputPath = const outputPath =
...@@ -797,6 +823,16 @@ export default async function getBaseWebpackConfig( ...@@ -797,6 +823,16 @@ export default async function getBaseWebpackConfig(
? path.join(distDir, SERVER_DIRECTORY) ? path.join(distDir, SERVER_DIRECTORY)
: distDir : distDir
const reactServerCondition = [
'react-server',
...mainFieldsPerCompiler[
isEdgeServer ? COMPILER_NAMES.edgeServer : COMPILER_NAMES.server
],
'node',
'import',
'require',
]
const clientEntries = isClient const clientEntries = isClient
? ({ ? ({
// Backwards compatibility // Backwards compatibility
...@@ -914,18 +950,6 @@ export default async function getBaseWebpackConfig( ...@@ -914,18 +950,6 @@ export default async function getBaseWebpackConfig(
] ]
} }
const mainFieldsPerCompiler: Record<typeof compilerType, string[]> = {
[COMPILER_NAMES.server]: ['main', 'module'],
[COMPILER_NAMES.client]: ['browser', 'module', 'main'],
[COMPILER_NAMES.edgeServer]: [
'edge-light',
'worker',
'browser',
'module',
'main',
],
}
const reactDir = path.dirname(require.resolve('react/package.json')) const reactDir = path.dirname(require.resolve('react/package.json'))
const reactDomDir = path.dirname(require.resolve('react-dom/package.json')) const reactDomDir = path.dirname(require.resolve('react-dom/package.json'))
let hasOptionalOTELAPIPackage = false let hasOptionalOTELAPIPackage = false
...@@ -1725,17 +1749,7 @@ export default async function getBaseWebpackConfig( ...@@ -1725,17 +1749,7 @@ export default async function getBaseWebpackConfig(
], ],
}, },
resolve: { resolve: {
conditionNames: [ conditionNames: reactServerCondition,
'react-server',
...mainFieldsPerCompiler[
isEdgeServer
? COMPILER_NAMES.edgeServer
: COMPILER_NAMES.server
],
'node',
'import',
'require',
],
alias: { alias: {
// If missing the alias override here, the default alias will be used which aliases // If missing the alias override here, the default alias will be used which aliases
// react to the direct file path, not the package name. In that case the condition // react to the direct file path, not the package name. In that case the condition
...@@ -1861,14 +1875,6 @@ export default async function getBaseWebpackConfig( ...@@ -1861,14 +1875,6 @@ export default async function getBaseWebpackConfig(
}, },
] ]
: []), : []),
{
test: /\.(js|cjs|mjs)$/,
issuerLayer: WEBPACK_LAYERS.api,
parser: {
// Switch back to normal URL handling
url: true,
},
},
{ {
oneOf: [ oneOf: [
{ {
...@@ -1878,7 +1884,7 @@ export default async function getBaseWebpackConfig( ...@@ -1878,7 +1884,7 @@ export default async function getBaseWebpackConfig(
// Switch back to normal URL handling // Switch back to normal URL handling
url: true, url: true,
}, },
use: defaultLoaders.babel, use: loaderForAPIRoutes,
}, },
{ {
...codeCondition, ...codeCondition,
...@@ -1891,12 +1897,12 @@ export default async function getBaseWebpackConfig( ...@@ -1891,12 +1897,12 @@ export default async function getBaseWebpackConfig(
test: codeCondition.test, test: codeCondition.test,
issuerLayer: WEBPACK_LAYERS.server, issuerLayer: WEBPACK_LAYERS.server,
exclude: [staticGenerationAsyncStorageRegex], exclude: [staticGenerationAsyncStorageRegex],
use: swcLoaderForRSC, use: swcLoaderForServerLayer,
}, },
{ {
test: codeCondition.test, test: codeCondition.test,
resourceQuery: /__edge_ssr_entry__/, resourceQuery: /__edge_ssr_entry__/,
use: swcLoaderForRSC, use: swcLoaderForServerLayer,
}, },
] ]
: []), : []),
......
// You can still import React and Next's client component APIs from the server
// they won't be poisoned by the environment.
// eslint-disable-next-line no-unused-vars
import { useState } from 'react'
import 'next/headers'
export default function (_, res) {
res.end('Hello from import-test.js')
}
...@@ -35,6 +35,7 @@ describe('app dir - rsc basics', () => { ...@@ -35,6 +35,7 @@ describe('app dir - rsc basics', () => {
'styled-components': '6.0.0-beta.5', 'styled-components': '6.0.0-beta.5',
react: 'latest', react: 'latest',
'react-dom': 'latest', 'react-dom': 'latest',
'server-only': 'latest',
}, },
packageJson: { packageJson: {
scripts: { scripts: {
...@@ -430,6 +431,11 @@ describe('app dir - rsc basics', () => { ...@@ -430,6 +431,11 @@ describe('app dir - rsc basics', () => {
}) })
}) })
it('should not apply rsc syntax checks in pages/api', async () => {
const res = await next.fetch('/api/import-test')
expect(await res.text()).toBe('Hello from import-test.js')
})
// disable this flaky test // disable this flaky test
it.skip('should support partial hydration with inlined server data in browser', async () => { it.skip('should support partial hydration with inlined server data in browser', async () => {
// Should end up with "next_streaming_data". // Should end up with "next_streaming_data".
......
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