Commit 1b3be708 authored by Jude Gao's avatar Jude Gao

working inline css

parent 491adda1
...@@ -95,7 +95,7 @@ export interface ClientReferenceManifest extends ClientReferenceManifestForRsc { ...@@ -95,7 +95,7 @@ export interface ClientReferenceManifest extends ClientReferenceManifestForRsc {
[moduleId: string]: ManifestNode [moduleId: string]: ManifestNode
} }
entryCSSFiles: { entryCSSFiles: {
[entry: string]: string[] [entry: string]: EntryCssFile[]
} }
entryJSFiles?: { entryJSFiles?: {
[entry: string]: string[] [entry: string]: string[]
...@@ -299,6 +299,14 @@ export class ClientReferenceManifestPlugin { ...@@ -299,6 +299,14 @@ export class ClientReferenceManifestPlugin {
manifest.entryCSSFiles[chunkEntryName] = entrypoint manifest.entryCSSFiles[chunkEntryName] = entrypoint
.getFiles() .getFiles()
.filter((f) => !f.startsWith('static/css/pages/') && f.endsWith('.css')) .filter((f) => !f.startsWith('static/css/pages/') && f.endsWith('.css'))
.map((file) => {
const source = compilation.assets[file].source()
// TODO: only do this when inlineCss is enabled
return {
path: file,
content: typeof source === 'string' ? source : source.toString(),
}
})
const requiredChunks = getAppPathRequiredChunks(entrypoint, rootMainFiles) const requiredChunks = getAppPathRequiredChunks(entrypoint, rootMainFiles)
const recordModule = (modId: ModuleId, mod: webpack.NormalModule) => { const recordModule = (modId: ModuleId, mod: webpack.NormalModule) => {
......
...@@ -358,6 +358,7 @@ async function exportAppImpl( ...@@ -358,6 +358,7 @@ async function exportAppImpl(
expireTime: nextConfig.expireTime, expireTime: nextConfig.expireTime,
after: nextConfig.experimental.after ?? false, after: nextConfig.experimental.after ?? false,
dynamicIO: nextConfig.experimental.dynamicIO ?? false, dynamicIO: nextConfig.experimental.dynamicIO ?? false,
inlineCss: nextConfig.experimental.inlineCss ?? false,
}, },
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength, reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,
} }
......
...@@ -21,6 +21,7 @@ import type { LoaderTree } from '../lib/app-dir-module' ...@@ -21,6 +21,7 @@ import type { LoaderTree } from '../lib/app-dir-module'
import type { AppPageModule } from '../route-modules/app-page/module' import type { AppPageModule } from '../route-modules/app-page/module'
import type { import type {
ClientReferenceManifest, ClientReferenceManifest,
EntryCssFile,
ManifestNode, ManifestNode,
} from '../../build/webpack/plugins/flight-manifest-plugin' } from '../../build/webpack/plugins/flight-manifest-plugin'
import type { DeepReadonly } from '../../shared/lib/deep-readonly' import type { DeepReadonly } from '../../shared/lib/deep-readonly'
...@@ -690,7 +691,7 @@ async function getRSCPayload( ...@@ -690,7 +691,7 @@ async function getRSCPayload(
ctx: AppRenderContext, ctx: AppRenderContext,
is404: boolean is404: boolean
): Promise<InitialRSCPayload & { P: React.ReactNode }> { ): Promise<InitialRSCPayload & { P: React.ReactNode }> {
const injectedCSS = new Set<string>() const injectedCSS = new Set<EntryCssFile>()
const injectedJS = new Set<string>() const injectedJS = new Set<string>()
const injectedFontPreloadTags = new Set<string>() const injectedFontPreloadTags = new Set<string>()
let missingSlots: Set<string> | undefined let missingSlots: Set<string> | undefined
......
...@@ -4,7 +4,9 @@ import { getLinkAndScriptTags } from './get-css-inlined-link-tags' ...@@ -4,7 +4,9 @@ import { getLinkAndScriptTags } from './get-css-inlined-link-tags'
import type { AppRenderContext } from './app-render' import type { AppRenderContext } from './app-render'
import { getAssetQueryString } from './get-asset-query-string' import { getAssetQueryString } from './get-asset-query-string'
import { encodeURIPath } from '../../shared/lib/encode-uri-path' import { encodeURIPath } from '../../shared/lib/encode-uri-path'
import type { EntryCssFile } from '../../build/webpack/plugins/flight-manifest-plugin'
// [STEP 1] TODO: consolidate this with get-layer-assets.tsx
export async function createComponentStylesAndScripts({ export async function createComponentStylesAndScripts({
filePath, filePath,
getComponent, getComponent,
...@@ -14,7 +16,7 @@ export async function createComponentStylesAndScripts({ ...@@ -14,7 +16,7 @@ export async function createComponentStylesAndScripts({
}: { }: {
filePath: string filePath: string
getComponent: () => any getComponent: () => any
injectedCSS: Set<string> injectedCSS: Set<EntryCssFile>
injectedJS: Set<string> injectedJS: Set<string>
ctx: AppRenderContext ctx: AppRenderContext
}): Promise<[React.ComponentType<any>, React.ReactNode, React.ReactNode]> { }): Promise<[React.ComponentType<any>, React.ReactNode, React.ReactNode]> {
...@@ -26,9 +28,9 @@ export async function createComponentStylesAndScripts({ ...@@ -26,9 +28,9 @@ export async function createComponentStylesAndScripts({
) )
const styles = cssHrefs const styles = cssHrefs
? cssHrefs.map((href, index) => { ? cssHrefs.map((entryCssFile, index) => {
const fullHref = `${ctx.assetPrefix}/_next/${encodeURIPath( const fullHref = `${ctx.assetPrefix}/_next/${encodeURIPath(
href entryCssFile.path
)}${getAssetQueryString(ctx, true)}` )}${getAssetQueryString(ctx, true)}`
// `Precedence` is an opt-in signal for React to handle resource // `Precedence` is an opt-in signal for React to handle resource
...@@ -38,7 +40,9 @@ export async function createComponentStylesAndScripts({ ...@@ -38,7 +40,9 @@ export async function createComponentStylesAndScripts({
// for different stylesheets, so their order will be kept. // for different stylesheets, so their order will be kept.
// https://github.com/facebook/react/pull/25060 // https://github.com/facebook/react/pull/25060
const precedence = const precedence =
process.env.NODE_ENV === 'development' ? 'next_' + href : 'next' process.env.NODE_ENV === 'development'
? 'next_' + entryCssFile.path
: 'next'
return ( return (
<link <link
......
...@@ -22,6 +22,7 @@ import type { LoadingModuleData } from '../../shared/lib/app-router-context.shar ...@@ -22,6 +22,7 @@ import type { LoadingModuleData } from '../../shared/lib/app-router-context.shar
import type { Params } from '../request/params' import type { Params } from '../request/params'
import { workUnitAsyncStorage } from './work-unit-async-storage.external' import { workUnitAsyncStorage } from './work-unit-async-storage.external'
import { OUTLET_BOUNDARY_NAME } from '../../lib/metadata/metadata-constants' import { OUTLET_BOUNDARY_NAME } from '../../lib/metadata/metadata-constants'
import type { EntryCssFile } from '../../build/webpack/plugins/flight-manifest-plugin'
/** /**
* Use the provided loader tree to create the React Component tree. * Use the provided loader tree to create the React Component tree.
...@@ -32,7 +33,7 @@ export function createComponentTree(props: { ...@@ -32,7 +33,7 @@ export function createComponentTree(props: {
parentParams: Params parentParams: Params
rootLayoutIncluded: boolean rootLayoutIncluded: boolean
firstItem?: boolean firstItem?: boolean
injectedCSS: Set<string> injectedCSS: Set<EntryCssFile>
injectedJS: Set<string> injectedJS: Set<string>
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
getMetadataReady: () => Promise<void> getMetadataReady: () => Promise<void>
...@@ -80,7 +81,7 @@ async function createComponentTreeInternal({ ...@@ -80,7 +81,7 @@ async function createComponentTreeInternal({
parentParams: Params parentParams: Params
rootLayoutIncluded: boolean rootLayoutIncluded: boolean
firstItem?: boolean firstItem?: boolean
injectedCSS: Set<string> injectedCSS: Set<EntryCssFile>
injectedJS: Set<string> injectedJS: Set<string>
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
getMetadataReady: () => Promise<void> getMetadataReady: () => Promise<void>
......
import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin' import type {
ClientReferenceManifest,
EntryCssFile,
} from '../../build/webpack/plugins/flight-manifest-plugin'
import type { DeepReadonly } from '../../shared/lib/deep-readonly' import type { DeepReadonly } from '../../shared/lib/deep-readonly'
/** /**
...@@ -7,12 +10,12 @@ import type { DeepReadonly } from '../../shared/lib/deep-readonly' ...@@ -7,12 +10,12 @@ import type { DeepReadonly } from '../../shared/lib/deep-readonly'
export function getLinkAndScriptTags( export function getLinkAndScriptTags(
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>, clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
filePath: string, filePath: string,
injectedCSS: Set<string>, injectedCSS: Set<EntryCssFile>,
injectedScripts: Set<string>, injectedScripts: Set<string>,
collectNewImports?: boolean collectNewImports?: boolean
): { styles: string[]; scripts: string[] } { ): { styles: EntryCssFile[]; scripts: string[] } {
const filePathWithoutExt = filePath.replace(/\.[^.]+$/, '') const filePathWithoutExt = filePath.replace(/\.[^.]+$/, '')
const cssChunks = new Set<string>() const cssChunks = new Set<EntryCssFile>()
const jsChunks = new Set<string>() const jsChunks = new Set<string>()
const entryCSSFiles = const entryCSSFiles =
......
...@@ -5,6 +5,7 @@ import type { AppRenderContext } from './app-render' ...@@ -5,6 +5,7 @@ import type { AppRenderContext } from './app-render'
import { getAssetQueryString } from './get-asset-query-string' import { getAssetQueryString } from './get-asset-query-string'
import { encodeURIPath } from '../../shared/lib/encode-uri-path' import { encodeURIPath } from '../../shared/lib/encode-uri-path'
import type { PreloadCallbacks } from './types' import type { PreloadCallbacks } from './types'
import type { EntryCssFile } from '../../build/webpack/plugins/flight-manifest-plugin'
export function getLayerAssets({ export function getLayerAssets({
ctx, ctx,
...@@ -15,7 +16,7 @@ export function getLayerAssets({ ...@@ -15,7 +16,7 @@ export function getLayerAssets({
preloadCallbacks, preloadCallbacks,
}: { }: {
layoutOrPagePath: string | undefined layoutOrPagePath: string | undefined
injectedCSS: Set<string> injectedCSS: Set<EntryCssFile>
injectedJS: Set<string> injectedJS: Set<string>
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
ctx: AppRenderContext ctx: AppRenderContext
...@@ -73,7 +74,18 @@ export function getLayerAssets({ ...@@ -73,7 +74,18 @@ export function getLayerAssets({
} }
const styles = styleTags const styles = styleTags
? styleTags.map((href, index) => { ? styleTags.map((entryCssFile, index) => {
// `Precedence` is an opt-in signal for React to handle resource
// loading and deduplication, etc. It's also used as the key to sort
// resources so they will be injected in the correct order.
// During HMR, it's critical to use different `precedence` values
// for different stylesheets, so their order will be kept.
// https://github.com/facebook/react/pull/25060
const precedence =
process.env.NODE_ENV === 'development'
? 'next_' + entryCssFile.path
: 'next'
// In dev, Safari and Firefox will cache the resource during HMR: // In dev, Safari and Firefox will cache the resource during HMR:
// - https://github.com/vercel/next.js/issues/5860 // - https://github.com/vercel/next.js/issues/5860
// - https://bugs.webkit.org/show_bug.cgi?id=187726 // - https://bugs.webkit.org/show_bug.cgi?id=187726
...@@ -81,17 +93,26 @@ export function getLayerAssets({ ...@@ -81,17 +93,26 @@ export function getLayerAssets({
// development. We need to also make sure that the number is always // development. We need to also make sure that the number is always
// increasing. // increasing.
const fullHref = `${ctx.assetPrefix}/_next/${encodeURIPath( const fullHref = `${ctx.assetPrefix}/_next/${encodeURIPath(
href entryCssFile.path
)}${getAssetQueryString(ctx, true)}` )}${getAssetQueryString(ctx, true)}`
// `Precedence` is an opt-in signal for React to handle resource if (
// loading and deduplication, etc. It's also used as the key to sort process.env.NEXT_RUNTIME !== 'edge' &&
// resources so they will be injected in the correct order. ctx.renderOpts.experimental.inlineCss
// During HMR, it's critical to use different `precedence` values ) {
// for different stylesheets, so their order will be kept. return (
// https://github.com/facebook/react/pull/25060 <style
const precedence = key={index}
process.env.NODE_ENV === 'development' ? 'next_' + href : 'next' dangerouslySetInnerHTML={{
__html: entryCssFile.content,
}}
nonce={ctx.nonce}
// @ts-ignore
precedence={precedence}
href={fullHref}
/>
)
}
preloadCallbacks.push(() => { preloadCallbacks.push(() => {
ctx.componentMod.preloadStyle( ctx.componentMod.preloadStyle(
...@@ -100,6 +121,7 @@ export function getLayerAssets({ ...@@ -100,6 +121,7 @@ export function getLayerAssets({
ctx.nonce ctx.nonce
) )
}) })
return ( return (
<link <link
rel="stylesheet" rel="stylesheet"
......
...@@ -132,6 +132,7 @@ export type ServerOnInstrumentationRequestError = ( ...@@ -132,6 +132,7 @@ export type ServerOnInstrumentationRequestError = (
) => void | Promise<void> ) => void | Promise<void>
export interface RenderOptsPartial { export interface RenderOptsPartial {
distDir?: string
previewProps: __ApiPreviewProps | undefined previewProps: __ApiPreviewProps | undefined
err?: Error | null err?: Error | null
dev?: boolean dev?: boolean
...@@ -182,6 +183,7 @@ export interface RenderOptsPartial { ...@@ -182,6 +183,7 @@ export interface RenderOptsPartial {
clientTraceMetadata: string[] | undefined clientTraceMetadata: string[] | undefined
after: boolean after: boolean
dynamicIO: boolean dynamicIO: boolean
inlineCss: boolean
} }
postponed?: string postponed?: string
......
...@@ -21,6 +21,7 @@ import { ...@@ -21,6 +21,7 @@ import {
addSearchParamsIfPageSegment, addSearchParamsIfPageSegment,
} from '../../shared/lib/segment' } from '../../shared/lib/segment'
import { createComponentTree } from './create-component-tree' import { createComponentTree } from './create-component-tree'
import type { EntryCssFile } from '../../build/webpack/plugins/flight-manifest-plugin'
/** /**
* Use router state to decide at what common layout to render the page. * Use router state to decide at what common layout to render the page.
...@@ -49,7 +50,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -49,7 +50,7 @@ export async function walkTreeWithFlightRouterState({
flightRouterState?: FlightRouterState flightRouterState?: FlightRouterState
parentRendered?: boolean parentRendered?: boolean
rscPayloadHead: React.ReactNode rscPayloadHead: React.ReactNode
injectedCSS: Set<string> injectedCSS: Set<EntryCssFile>
injectedJS: Set<string> injectedJS: Set<string>
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
rootLayoutIncluded: boolean rootLayoutIncluded: boolean
......
...@@ -593,6 +593,7 @@ export default abstract class Server< ...@@ -593,6 +593,7 @@ export default abstract class Server<
clientTraceMetadata: this.nextConfig.experimental.clientTraceMetadata, clientTraceMetadata: this.nextConfig.experimental.clientTraceMetadata,
after: this.nextConfig.experimental.after ?? false, after: this.nextConfig.experimental.after ?? false,
dynamicIO: this.nextConfig.experimental.dynamicIO ?? false, dynamicIO: this.nextConfig.experimental.dynamicIO ?? false,
inlineCss: this.nextConfig.experimental.inlineCss ?? false,
}, },
onInstrumentationRequestError: onInstrumentationRequestError:
this.instrumentationOnRequestError.bind(this), this.instrumentationOnRequestError.bind(this),
...@@ -2443,6 +2444,7 @@ export default abstract class Server< ...@@ -2443,6 +2444,7 @@ export default abstract class Server<
onAfterTaskError: undefined, onAfterTaskError: undefined,
// only available in dev // only available in dev
setAppIsrStatus: (this as any).setAppIsrStatus, setAppIsrStatus: (this as any).setAppIsrStatus,
distDir: this.distDir,
} }
if (isDebugStaticShell || isDebugDynamicAccesses) { if (isDebugStaticShell || isDebugDynamicAccesses) {
......
...@@ -293,6 +293,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -293,6 +293,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
disableOptimizedLoading: z.boolean().optional(), disableOptimizedLoading: z.boolean().optional(),
disablePostcssPresetEnv: z.boolean().optional(), disablePostcssPresetEnv: z.boolean().optional(),
dynamicIO: z.boolean().optional(), dynamicIO: z.boolean().optional(),
inlineCss: z.boolean().optional(),
esmExternals: z.union([z.boolean(), z.literal('loose')]).optional(), esmExternals: z.union([z.boolean(), z.literal('loose')]).optional(),
serverActions: z serverActions: z
.object({ .object({
......
...@@ -558,6 +558,12 @@ export interface ExperimentalConfig { ...@@ -558,6 +558,12 @@ export interface ExperimentalConfig {
* unless explicitly cached. * unless explicitly cached.
*/ */
dynamicIO?: boolean dynamicIO?: boolean
/**
* Render <style> tags inline in the HTML for imported CSS assets.
* This is always disabled in the edge runtime.
*/
inlineCss?: boolean
} }
export type ExportPathMap = { export type ExportPathMap = {
......
import './global.css'
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Home() {
return <p>Home</p>
}
import { nextTestSetup } from 'e2e-utils'
describe('app dir - css - experimental inline css', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should render page with correct styles', async () => {
const browser = await next.browser('/')
const inlineStyleTag = await browser.elementByCss('style')
expect(await inlineStyleTag.text()).toContain('color')
const p = await browser.elementByCss('p')
expect(await p.getComputedCss('color')).toBe('rgb(255, 255, 0)') // yellow
})
})
module.exports = {
experimental: {
inlineCss: 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