Unverified Commit 481950c3 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Error for ssg and ssr exports from client components in build time (#40106)

Follow up for #39953

Detect invalid gSSP/gSP exports in page or layout client components in build time instead of checking them in runtime, in this way we can:
* Error to user eariler with traced file path, help user find the incorrect usage easier
* Make the flight client loader simpler, headless, aligned with react
Co-authored-by: 's avatarJJ Kasper <22380829+ijjk@users.noreply.github.com>
parent 591f341d
...@@ -5,31 +5,50 @@ ...@@ -5,31 +5,50 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
import path from 'path'
import { checkExports } from '../../../analysis/get-page-static-info' import { checkExports } from '../../../analysis/get-page-static-info'
import { parse } from '../../../swc' import { parse } from '../../../swc'
function containsPath(parent: string, child: string) {
const relation = path.relative(parent, child)
return !!relation && !relation.startsWith('..') && !path.isAbsolute(relation)
}
export default async function transformSource( export default async function transformSource(
this: any, this: any,
source: string source: string
): Promise<string> { ): Promise<string> {
const { resourcePath } = this if (typeof source !== 'string') {
const transformedSource = source
if (typeof transformedSource !== 'string') {
throw new Error('Expected source to have been transformed to a string.') throw new Error('Expected source to have been transformed to a string.')
} }
const swcAST = await parse(transformedSource, { const appDir = path.join(this.rootContext, 'app')
filename: resourcePath, const isUnderAppDir = containsPath(appDir, this.resourcePath)
isModule: 'unknown', const filename = path.basename(this.resourcePath)
}) const isPageOrLayoutFile = /^(page|layout)\.client\.\w+$/.test(filename)
const { ssg, ssr } = checkExports(swcAST)
const createError = (name: string) =>
new Error(
`${name} is not supported in client components.\nFrom: ${this.resourcePath}`
)
if (isUnderAppDir && isPageOrLayoutFile) {
const swcAST = await parse(source, {
filename: this.resourcePath,
isModule: 'unknown',
})
const { ssg, ssr } = checkExports(swcAST)
if (ssg) {
this.emitError(createError('getStaticProps'))
}
if (ssr) {
this.emitError(createError('getServerSideProps'))
}
}
const output = ` const output = `
const { createProxy } = require("next/dist/build/webpack/loaders/next-flight-client-loader/module-proxy")\n const { createProxy } = require("next/dist/build/webpack/loaders/next-flight-client-loader/module-proxy")\n
module.exports = createProxy(${JSON.stringify( module.exports = createProxy(${JSON.stringify(this.resourcePath)})
resourcePath
)}, { ssr: ${ssr}, ssg: ${ssg} })
` `
return output return output
} }
...@@ -38,9 +38,6 @@ const proxyHandlers: ProxyHandler<object> = { ...@@ -38,9 +38,6 @@ const proxyHandlers: ProxyHandler<object> = {
// whole object or just the default export. // whole object or just the default export.
name: '', name: '',
async: target.async, async: target.async,
ssr: target.ssr,
ssg: target.ssg,
} }
return true return true
case 'then': case 'then':
...@@ -57,9 +54,6 @@ const proxyHandlers: ProxyHandler<object> = { ...@@ -57,9 +54,6 @@ const proxyHandlers: ProxyHandler<object> = {
filepath: target.filepath, filepath: target.filepath,
name: '*', // Represents the whole object instead of a particular import. name: '*', // Represents the whole object instead of a particular import.
async: true, async: true,
ssr: target.ssr,
ssg: target.ssg,
} }
return Promise.resolve( return Promise.resolve(
resolve(new Proxy(moduleReference, proxyHandlers)) resolve(new Proxy(moduleReference, proxyHandlers))
...@@ -74,11 +68,6 @@ const proxyHandlers: ProxyHandler<object> = { ...@@ -74,11 +68,6 @@ const proxyHandlers: ProxyHandler<object> = {
return then return then
} }
break break
case 'ssg':
return target.ssg
case 'ssr':
return target.ssr
default: default:
break break
} }
...@@ -102,18 +91,12 @@ const proxyHandlers: ProxyHandler<object> = { ...@@ -102,18 +91,12 @@ const proxyHandlers: ProxyHandler<object> = {
}, },
} }
export function createProxy( export function createProxy(moduleId: string) {
moduleId: string,
{ ssr, ssg }: { ssr: boolean; ssg: boolean }
) {
const moduleReference = { const moduleReference = {
$$typeof: MODULE_REFERENCE, $$typeof: MODULE_REFERENCE,
filepath: moduleId, filepath: moduleId,
name: '*', // Represents the whole object instead of a particular import. name: '*', // Represents the whole object instead of a particular import.
async: false, async: false,
ssr,
ssg,
} }
return new Proxy(moduleReference, proxyHandlers) return new Proxy(moduleReference, proxyHandlers)
} }
...@@ -639,20 +639,6 @@ export async function renderToHTMLOrFlight( ...@@ -639,20 +639,6 @@ export async function renderToHTMLOrFlight(
const isClientComponentModule = const isClientComponentModule =
layoutOrPageMod && !layoutOrPageMod.hasOwnProperty('__next_rsc__') layoutOrPageMod && !layoutOrPageMod.hasOwnProperty('__next_rsc__')
// Only server components can have getServerSideProps / getStaticProps
// TODO-APP: friendly error with correct stacktrace. Potentially this can be part of the compiler instead.
if (isClientComponentModule) {
if (layoutOrPageMod.ssr) {
throw new Error(
'getServerSideProps is not supported on Client Components'
)
}
if (layoutOrPageMod.ssg) {
throw new Error('getStaticProps is not supported on Client Components')
}
}
/** /**
* The React Component to render. * The React Component to render.
*/ */
......
export function getServerSideProps() { // export function getServerSideProps() { { props: {} } }
return { props: {} }
}
export default function Page() { export default function Page() {
return null return 'client-gssp'
} }
export function getStaticProps() { // export function getStaticProps() { return { props: {} }}
return { props: {} }
}
export default function Page() { export default function Page() {
return null return 'client-gsp'
} }
import { createNext, FileRef } from 'e2e-utils' import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base' import { NextInstance } from 'test/lib/next-modes/base'
import { fetchViaHTTP, renderViaHTTP, waitFor } from 'next-test-utils' import { check, fetchViaHTTP, renderViaHTTP, waitFor } from 'next-test-utils'
import path from 'path' import path from 'path'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
...@@ -1023,31 +1023,64 @@ describe('app dir', () => { ...@@ -1023,31 +1023,64 @@ describe('app dir', () => {
}) })
}) })
it('should throw an error when getStaticProps is used', async () => { if (isDev) {
const res = await fetchViaHTTP( it('should throw an error when getServerSideProps is used', async () => {
next.url, const pageFile =
'/client-with-errors/get-static-props' 'app/client-with-errors/get-server-side-props/page.client.js'
) const content = await next.readFile(pageFile)
expect(res.status).toBe(500) const uncomment = content.replace(
expect(await res.text()).toContain( '// export function getServerSideProps',
isDev 'export function getServerSideProps'
? 'getStaticProps is not supported on Client Components' )
: 'Internal Server Error' await next.patchFile(pageFile, uncomment)
) const res = await fetchViaHTTP(
}) next.url,
'/client-with-errors/get-server-side-props'
)
await next.patchFile(pageFile, content)
it('should throw an error when getServerSideProps is used', async () => { await check(async () => {
const res = await fetchViaHTTP( const { status } = await fetchViaHTTP(
next.url, next.url,
'/client-with-errors/get-server-side-props' '/client-with-errors/get-server-side-props'
) )
expect(res.status).toBe(500) return status
expect(await res.text()).toContain( }, /200/)
isDev
? 'getServerSideProps is not supported on Client Components' expect(res.status).toBe(500)
: 'Internal Server Error' expect(await res.text()).toContain(
) 'getServerSideProps is not supported in client components'
}) )
})
it('should throw an error when getStaticProps is used', async () => {
const pageFile =
'app/client-with-errors/get-static-props/page.client.js'
const content = await next.readFile(pageFile)
const uncomment = content.replace(
'// export function getStaticProps',
'export function getStaticProps'
)
await next.patchFile(pageFile, uncomment)
const res = await fetchViaHTTP(
next.url,
'/client-with-errors/get-static-props'
)
await next.patchFile(pageFile, content)
await check(async () => {
const { status } = await fetchViaHTTP(
next.url,
'/client-with-errors/get-static-props'
)
return status
}, /200/)
expect(res.status).toBe(500)
expect(await res.text()).toContain(
'getStaticProps is not supported in client components'
)
})
}
}) })
describe('css support', () => { describe('css support', () => {
......
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