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

working inline css

parent 491adda1
......@@ -95,7 +95,7 @@ export interface ClientReferenceManifest extends ClientReferenceManifestForRsc {
[moduleId: string]: ManifestNode
}
entryCSSFiles: {
[entry: string]: string[]
[entry: string]: EntryCssFile[]
}
entryJSFiles?: {
[entry: string]: string[]
......@@ -299,6 +299,14 @@ export class ClientReferenceManifestPlugin {
manifest.entryCSSFiles[chunkEntryName] = entrypoint
.getFiles()
.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 recordModule = (modId: ModuleId, mod: webpack.NormalModule) => {
......
......@@ -358,6 +358,7 @@ async function exportAppImpl(
expireTime: nextConfig.expireTime,
after: nextConfig.experimental.after ?? false,
dynamicIO: nextConfig.experimental.dynamicIO ?? false,
inlineCss: nextConfig.experimental.inlineCss ?? false,
},
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,
}
......
......@@ -21,6 +21,7 @@ import type { LoaderTree } from '../lib/app-dir-module'
import type { AppPageModule } from '../route-modules/app-page/module'
import type {
ClientReferenceManifest,
EntryCssFile,
ManifestNode,
} from '../../build/webpack/plugins/flight-manifest-plugin'
import type { DeepReadonly } from '../../shared/lib/deep-readonly'
......@@ -690,7 +691,7 @@ async function getRSCPayload(
ctx: AppRenderContext,
is404: boolean
): Promise<InitialRSCPayload & { P: React.ReactNode }> {
const injectedCSS = new Set<string>()
const injectedCSS = new Set<EntryCssFile>()
const injectedJS = new Set<string>()
const injectedFontPreloadTags = new Set<string>()
let missingSlots: Set<string> | undefined
......
......@@ -4,7 +4,9 @@ import { getLinkAndScriptTags } from './get-css-inlined-link-tags'
import type { AppRenderContext } from './app-render'
import { getAssetQueryString } from './get-asset-query-string'
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({
filePath,
getComponent,
......@@ -14,7 +16,7 @@ export async function createComponentStylesAndScripts({
}: {
filePath: string
getComponent: () => any
injectedCSS: Set<string>
injectedCSS: Set<EntryCssFile>
injectedJS: Set<string>
ctx: AppRenderContext
}): Promise<[React.ComponentType<any>, React.ReactNode, React.ReactNode]> {
......@@ -26,9 +28,9 @@ export async function createComponentStylesAndScripts({
)
const styles = cssHrefs
? cssHrefs.map((href, index) => {
? cssHrefs.map((entryCssFile, index) => {
const fullHref = `${ctx.assetPrefix}/_next/${encodeURIPath(
href
entryCssFile.path
)}${getAssetQueryString(ctx, true)}`
// `Precedence` is an opt-in signal for React to handle resource
......@@ -38,7 +40,9 @@ export async function createComponentStylesAndScripts({
// for different stylesheets, so their order will be kept.
// https://github.com/facebook/react/pull/25060
const precedence =
process.env.NODE_ENV === 'development' ? 'next_' + href : 'next'
process.env.NODE_ENV === 'development'
? 'next_' + entryCssFile.path
: 'next'
return (
<link
......
......@@ -22,6 +22,7 @@ import type { LoadingModuleData } from '../../shared/lib/app-router-context.shar
import type { Params } from '../request/params'
import { workUnitAsyncStorage } from './work-unit-async-storage.external'
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.
......@@ -32,7 +33,7 @@ export function createComponentTree(props: {
parentParams: Params
rootLayoutIncluded: boolean
firstItem?: boolean
injectedCSS: Set<string>
injectedCSS: Set<EntryCssFile>
injectedJS: Set<string>
injectedFontPreloadTags: Set<string>
getMetadataReady: () => Promise<void>
......@@ -80,7 +81,7 @@ async function createComponentTreeInternal({
parentParams: Params
rootLayoutIncluded: boolean
firstItem?: boolean
injectedCSS: Set<string>
injectedCSS: Set<EntryCssFile>
injectedJS: Set<string>
injectedFontPreloadTags: Set<string>
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'
/**
......@@ -7,12 +10,12 @@ import type { DeepReadonly } from '../../shared/lib/deep-readonly'
export function getLinkAndScriptTags(
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
filePath: string,
injectedCSS: Set<string>,
injectedCSS: Set<EntryCssFile>,
injectedScripts: Set<string>,
collectNewImports?: boolean
): { styles: string[]; scripts: string[] } {
): { styles: EntryCssFile[]; scripts: string[] } {
const filePathWithoutExt = filePath.replace(/\.[^.]+$/, '')
const cssChunks = new Set<string>()
const cssChunks = new Set<EntryCssFile>()
const jsChunks = new Set<string>()
const entryCSSFiles =
......
......@@ -5,6 +5,7 @@ import type { AppRenderContext } from './app-render'
import { getAssetQueryString } from './get-asset-query-string'
import { encodeURIPath } from '../../shared/lib/encode-uri-path'
import type { PreloadCallbacks } from './types'
import type { EntryCssFile } from '../../build/webpack/plugins/flight-manifest-plugin'
export function getLayerAssets({
ctx,
......@@ -15,7 +16,7 @@ export function getLayerAssets({
preloadCallbacks,
}: {
layoutOrPagePath: string | undefined
injectedCSS: Set<string>
injectedCSS: Set<EntryCssFile>
injectedJS: Set<string>
injectedFontPreloadTags: Set<string>
ctx: AppRenderContext
......@@ -73,7 +74,18 @@ export function getLayerAssets({
}
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:
// - https://github.com/vercel/next.js/issues/5860
// - https://bugs.webkit.org/show_bug.cgi?id=187726
......@@ -81,17 +93,26 @@ export function getLayerAssets({
// development. We need to also make sure that the number is always
// increasing.
const fullHref = `${ctx.assetPrefix}/_next/${encodeURIPath(
href
entryCssFile.path
)}${getAssetQueryString(ctx, true)}`
// `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_' + href : 'next'
if (
process.env.NEXT_RUNTIME !== 'edge' &&
ctx.renderOpts.experimental.inlineCss
) {
return (
<style
key={index}
dangerouslySetInnerHTML={{
__html: entryCssFile.content,
}}
nonce={ctx.nonce}
// @ts-ignore
precedence={precedence}
href={fullHref}
/>
)
}
preloadCallbacks.push(() => {
ctx.componentMod.preloadStyle(
......@@ -100,6 +121,7 @@ export function getLayerAssets({
ctx.nonce
)
})
return (
<link
rel="stylesheet"
......
......@@ -132,6 +132,7 @@ export type ServerOnInstrumentationRequestError = (
) => void | Promise<void>
export interface RenderOptsPartial {
distDir?: string
previewProps: __ApiPreviewProps | undefined
err?: Error | null
dev?: boolean
......@@ -182,6 +183,7 @@ export interface RenderOptsPartial {
clientTraceMetadata: string[] | undefined
after: boolean
dynamicIO: boolean
inlineCss: boolean
}
postponed?: string
......
......@@ -21,6 +21,7 @@ import {
addSearchParamsIfPageSegment,
} from '../../shared/lib/segment'
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.
......@@ -49,7 +50,7 @@ export async function walkTreeWithFlightRouterState({
flightRouterState?: FlightRouterState
parentRendered?: boolean
rscPayloadHead: React.ReactNode
injectedCSS: Set<string>
injectedCSS: Set<EntryCssFile>
injectedJS: Set<string>
injectedFontPreloadTags: Set<string>
rootLayoutIncluded: boolean
......
......@@ -593,6 +593,7 @@ export default abstract class Server<
clientTraceMetadata: this.nextConfig.experimental.clientTraceMetadata,
after: this.nextConfig.experimental.after ?? false,
dynamicIO: this.nextConfig.experimental.dynamicIO ?? false,
inlineCss: this.nextConfig.experimental.inlineCss ?? false,
},
onInstrumentationRequestError:
this.instrumentationOnRequestError.bind(this),
......@@ -2443,6 +2444,7 @@ export default abstract class Server<
onAfterTaskError: undefined,
// only available in dev
setAppIsrStatus: (this as any).setAppIsrStatus,
distDir: this.distDir,
}
if (isDebugStaticShell || isDebugDynamicAccesses) {
......
......@@ -293,6 +293,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
disableOptimizedLoading: z.boolean().optional(),
disablePostcssPresetEnv: z.boolean().optional(),
dynamicIO: z.boolean().optional(),
inlineCss: z.boolean().optional(),
esmExternals: z.union([z.boolean(), z.literal('loose')]).optional(),
serverActions: z
.object({
......
......@@ -558,6 +558,12 @@ export interface ExperimentalConfig {
* unless explicitly cached.
*/
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 = {
......
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