Unverified Commit 7921b675 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Leverage mini css plugin hmr for app dir (#38830)

Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
parent 5752d4a6
......@@ -470,7 +470,8 @@ export const css = curry(async function css(
)
}
if (ctx.isClient && ctx.isProduction) {
// Enable full mini-css-extract-plugin hmr for prod mode pages or app dir
if (ctx.isClient && (ctx.isProduction || ctx.experimental.appDir)) {
// Extract CSS as CSS file(s) in the client-side production bundle.
const MiniCssExtractPlugin =
require('../../../plugins/mini-css-extract-plugin').default
......@@ -478,8 +479,12 @@ export const css = curry(async function css(
plugin(
// @ts-ignore webpack 5 compat
new MiniCssExtractPlugin({
filename: 'static/css/[contenthash].css',
chunkFilename: 'static/css/[contenthash].css',
filename: ctx.isProduction
? 'static/css/[contenthash].css'
: 'static/css/[name].css',
chunkFilename: ctx.isProduction
? 'static/css/[contenthash].css'
: 'static/css/[name].css',
// Next.js guarantees that CSS order "doesn't matter", due to imposed
// restrictions:
// 1. Global CSS can only be defined in a single entrypoint (_app)
......
......@@ -9,37 +9,30 @@ export function getClientStyleLoader({
isDevelopment: boolean
assetPrefix: string
}): webpack.RuleSetUseItem {
if (isDevelopment) {
// Keep next-style-loader for development mode in `pages/`
if (isDevelopment && !isAppDir) {
return {
loader: 'next-style-loader',
options: {
insert: isAppDir
? function (element: Node) {
// There is currently no anchor element in <head>.
// We temporarily insert the element as the last child
// of the first <head>.
const head = document.querySelector('head')!
head.insertBefore(element, head.lastChild)
}
: function (element: Node) {
// By default, style-loader injects CSS into the bottom
// of <head>. This causes ordering problems between dev
// and prod. To fix this, we render a <noscript> tag as
// an anchor for the styles to be placed before. These
// styles will be applied _before_ <style jsx global>.
insert: function (element: Node) {
// By default, style-loader injects CSS into the bottom
// of <head>. This causes ordering problems between dev
// and prod. To fix this, we render a <noscript> tag as
// an anchor for the styles to be placed before. These
// styles will be applied _before_ <style jsx global>.
// These elements should always exist. If they do not,
// this code should fail.
var anchorElement = document.querySelector(
'#__next_css__DO_NOT_USE__'
)!
var parentNode = anchorElement.parentNode! // Normally <head>
// These elements should always exist. If they do not,
// this code should fail.
var anchorElement = document.querySelector(
'#__next_css__DO_NOT_USE__'
)!
var parentNode = anchorElement.parentNode! // Normally <head>
// Each style tag should be placed right before our
// anchor. By inserting before and not after, we do not
// need to track the last inserted element.
parentNode.insertBefore(element, anchorElement)
},
// Each style tag should be placed right before our
// anchor. By inserting before and not after, we do not
// need to track the last inserted element.
parentNode.insertBefore(element, anchorElement)
},
},
}
}
......
......@@ -119,44 +119,20 @@ export class FlightManifestPlugin {
if (isCSSModule) {
if (!manifest[resource]) {
if (dev) {
const chunkIdNameMapping = (chunk.ids || []).map((chunkId) => {
return (
chunkId +
':' +
(chunk.name || chunk.id) +
(dev ? '' : '-' + chunk.hash)
)
})
manifest[resource] = {
default: {
id,
name: 'default',
chunks: chunkIdNameMapping,
},
}
moduleIdMapping[id]['default'] = {
id: ssrNamedModuleId,
name: 'default',
chunks: chunkIdNameMapping,
}
manifest.__ssr_module_mapping__ = moduleIdMapping
} else {
const chunks = [...chunk.files].filter((f) => f.endsWith('.css'))
manifest[resource] = {
default: {
id,
name: 'default',
chunks,
},
}
moduleIdMapping[id]['default'] = {
id: ssrNamedModuleId,
const chunks = [...chunk.files].filter((f) => f.endsWith('.css'))
manifest[resource] = {
default: {
id,
name: 'default',
chunks,
}
manifest.__ssr_module_mapping__ = moduleIdMapping
},
}
moduleIdMapping[id]['default'] = {
id: ssrNamedModuleId,
name: 'default',
chunks,
}
manifest.__ssr_module_mapping__ = moduleIdMapping
}
return
}
......
......@@ -33,16 +33,16 @@ self.__next_require__ = __webpack_require__
;(self as any).__next_chunk_load__ = (chunk: string) => {
if (!chunk) return Promise.resolve()
if (chunk.endsWith('.css')) {
const existingTag = document.querySelector(`link[href="${chunk}"]`)
const chunkPath = `/_next/${chunk}`
const existingTag = document.querySelector(`link[href="${chunkPath}"]`)
if (!existingTag) {
const link = document.createElement('link')
link.rel = 'stylesheet'
link.href = '/_next/' + chunk
link.href = chunkPath
document.head.appendChild(link)
}
return Promise.resolve()
}
const [chunkId, chunkFileName] = chunk.split(':')
chunkFilenameMap[chunkId] = `static/chunks/${chunkFileName}.js`
......@@ -147,73 +147,7 @@ function createResponseCache() {
}
const rscCache = createResponseCache()
async function loadCss(cssChunkInfoJson: string) {
const data = JSON.parse(cssChunkInfoJson)
await Promise.all(
data.chunks.map((chunkId: string) => {
// load css related chunks
return (self as any).__next_chunk_load__(chunkId)
})
)
// In development mode, import css in dev when it's wrapped by style loader.
// In production mode, css are standalone chunk that doesn't need to be imported.
if (data.id) {
return (self as any).__next_require__(data.id)
}
return Promise.resolve()
}
function createLoadFlightCssStream(onFlightCssLoaded: () => void) {
const promises: Promise<any>[] = []
let cssFlushed = false
const loadCssFromStreamData = (data: string) => {
if (data.startsWith('CSS')) {
const cssJson = data.slice(4).trim()
promises.push(loadCss(cssJson))
}
}
// TODO-APP: Refine the buffering code here to make it more correct.
let buffer = ''
const loadCssFromFlight = new TransformStream({
transform(chunk, controller) {
const process = (buf: string) => {
if (buf) {
if (buf.startsWith('CSS:')) {
loadCssFromStreamData(buf)
} else {
controller.enqueue(new TextEncoder().encode(buf))
if (!cssFlushed) {
cssFlushed = true
Promise.all(promises).then(() => onFlightCssLoaded())
}
}
}
}
const data = new TextDecoder().decode(chunk)
buffer += data
let index
while ((index = buffer.indexOf('\n')) !== -1) {
const line = buffer.slice(0, index + 1)
buffer = buffer.slice(index + 1)
process(line)
}
process(buffer)
buffer = ''
},
})
return loadCssFromFlight
}
function useInitialServerResponse(
cacheKey: string,
onFlightCssLoaded: () => void
) {
function useInitialServerResponse(cacheKey: string) {
const response = rscCache.get(cacheKey)
if (response) return response
......@@ -223,25 +157,17 @@ function useInitialServerResponse(
},
})
const newResponse = createFromReadableStream(
readable.pipeThrough(createLoadFlightCssStream(onFlightCssLoaded))
)
const newResponse = createFromReadableStream(readable)
rscCache.set(cacheKey, newResponse)
return newResponse
}
function ServerRoot({
cacheKey,
onFlightCssLoaded,
}: {
cacheKey: string
onFlightCssLoaded: () => Promise<void>
}) {
function ServerRoot({ cacheKey }: { cacheKey: string }) {
React.useEffect(() => {
rscCache.delete(cacheKey)
})
const response = useInitialServerResponse(cacheKey, onFlightCssLoaded)
const response = useInitialServerResponse(cacheKey)
const root = response.readRoot()
return root
}
......@@ -266,11 +192,11 @@ function RSCComponent(props: any) {
return <ServerRoot {...props} cacheKey={cacheKey} />
}
export function hydrate(opts?: { onFlightCssLoaded?: () => Promise<void> }) {
export function hydrate() {
renderReactElement(appElement!, () => (
<React.StrictMode>
<Root>
<RSCComponent onFlightCssLoaded={opts?.onFlightCssLoaded} />
<RSCComponent />
</Root>
</React.StrictMode>
))
......
import { hydrate, version } from './app-index'
import { displayContent } from './dev/fouc'
// TODO-APP: implement FOUC guard
// TODO-APP: hydration warning
......@@ -10,6 +7,6 @@ window.next = {
appDir: true,
}
hydrate({ onFlightCssLoaded: displayContent })
hydrate()
// TODO-APP: build indicator
......@@ -18,27 +18,6 @@ import {
// LayoutSegmentsContext,
} from './hooks-client-context'
async function loadCss(cssChunkInfoJson: string) {
const data = JSON.parse(cssChunkInfoJson)
await Promise.all(
data.chunks.map((chunkId: string) => {
// load css related chunks
return (self as any).__next_chunk_load__(chunkId)
})
)
// In development mode, import css in dev when it's wrapped by style loader.
// In production mode, css are standalone chunk that doesn't need to be imported.
if (data.id) {
;(self as any).__next_require__(data.id)
}
}
const loadCssFromStreamData = (data: string) => {
if (data.startsWith('CSS:')) {
loadCss(data.slice(4).trim())
}
}
function fetchFlight(url: URL, flightRouterStateData: string): ReadableStream {
const flightUrl = new URL(url)
const searchParams = flightUrl.searchParams
......@@ -47,35 +26,8 @@ function fetchFlight(url: URL, flightRouterStateData: string): ReadableStream {
const { readable, writable } = new TransformStream()
// TODO-APP: Refine the buffering code here to make it more correct.
let buffer = ''
const loadCssFromFlight = new TransformStream({
transform(chunk, controller) {
const process = (buf: string) => {
if (buf) {
if (buf.startsWith('CSS:')) {
loadCssFromStreamData(buf)
} else {
controller.enqueue(new TextEncoder().encode(buf))
}
}
}
const data = new TextDecoder().decode(chunk)
buffer += data
let index
while ((index = buffer.indexOf('\n')) !== -1) {
const line = buffer.slice(0, index + 1)
buffer = buffer.slice(index + 1)
process(line)
}
process(buffer)
buffer = ''
},
})
fetch(flightUrl.toString()).then((res) => {
res.body?.pipeThrough(loadCssFromFlight).pipeTo(writable)
res.body?.pipeTo(writable)
})
return readable
......
......@@ -16,7 +16,6 @@ import {
renderToInitialStream,
createBufferedTransformStream,
continueFromInitialStream,
createPrefixStream,
} from './node-web-streams-helper'
import { isDynamicRoute } from '../shared/lib/router/utils'
import { tryGetPreviewData } from './api-utils/node'
......@@ -113,8 +112,7 @@ function useFlightResponse(
writable: WritableStream<Uint8Array>,
cachePrefix: string,
req: ReadableStream<Uint8Array>,
serverComponentManifest: any,
cssFlightData: string
serverComponentManifest: any
) {
const id = cachePrefix + ',' + (React as any).useId()
let entry = rscCache.get(id)
......@@ -127,9 +125,7 @@ function useFlightResponse(
let bootstrapped = false
// We only attach CSS chunks to the inlined data.
const forwardReader = forwardStream
.pipeThrough(createPrefixStream(cssFlightData))
.getReader()
const forwardReader = forwardStream.getReader()
const writer = writable.getWriter()
function process() {
forwardReader.read().then(({ done, value }) => {
......@@ -176,8 +172,7 @@ function createServerComponentRenderer(
transformStream: TransformStream<Uint8Array, Uint8Array>
serverComponentManifest: NonNullable<RenderOpts['serverComponentManifest']>
serverContexts: Array<[ServerContextName: string, JSONValue: any]>
},
dev: boolean
}
) {
// We need to expose the `__webpack_require__` API globally for
// react-server-dom-webpack. This is a hack until we find a better way.
......@@ -191,12 +186,6 @@ function createServerComponentRenderer(
globalThis.__next_chunk_load__ = () => Promise.resolve()
}
const cssFlightData = getCssFlightData(
ComponentMod,
serverComponentManifest,
dev
)
let RSCStream: ReadableStream<Uint8Array>
const createRSCStream = () => {
if (!RSCStream) {
......@@ -218,8 +207,7 @@ function createServerComponentRenderer(
writable,
cachePrefix,
reqStream,
serverComponentManifest,
cssFlightData
serverComponentManifest
)
return response.readRoot()
}
......@@ -328,13 +316,10 @@ function getSegmentParam(segment: string): {
return null
}
function getCSSInlinedLinkTags(
function getCssInlinedLinkTags(
ComponentMod: any,
serverComponentManifest: any,
dev: boolean
serverComponentManifest: any
) {
if (dev) return []
const importedServerCSSFiles: string[] =
ComponentMod.__client__?.__next_rsc_css__ || []
......@@ -351,33 +336,6 @@ function getCSSInlinedLinkTags(
)
}
function getCssFlightData(
ComponentMod: any,
serverComponentManifest: any,
dev: boolean
) {
const importedServerCSSFiles: string[] =
ComponentMod.__client__?.__next_rsc_css__ || []
const cssFiles = importedServerCSSFiles.map(
(css) => serverComponentManifest[css].default
)
if (dev) {
// Keep `id` in dev mode css flight to require the css module
return cssFiles.map((css) => `CSS:${JSON.stringify(css)}`).join('\n') + '\n'
}
// Multiple css chunks could be merged into one by mini-css-extract-plugin,
// we use a set here to dedupe the css chunks in production.
const cssSet: Set<string> = cssFiles.reduce((res, css) => {
res.add(...css.chunks)
return res
}, new Set())
return cssSet.size ? `CSS:${JSON.stringify({ chunks: [...cssSet] })}\n` : ''
}
export async function renderToHTML(
req: IncomingMessage,
res: ServerResponse,
......@@ -403,7 +361,6 @@ export async function renderToHTML(
runtime,
ComponentMod,
} = renderOpts
const dev = !!renderOpts.dev
const isFlight = query.__flight__ !== undefined
......@@ -838,11 +795,6 @@ export async function renderToHTML(
return [actualSegment]
}
const cssFlightData = getCssFlightData(
ComponentMod,
serverComponentManifest,
dev
)
const flightData: FlightData = [
// TODO-APP: change walk to output without ''
(
......@@ -853,9 +805,7 @@ export async function renderToHTML(
return new RenderResult(
renderToReadableStream(flightData, serverComponentManifest, {
context: serverContexts,
})
.pipeThrough(createPrefixStream(cssFlightData))
.pipeThrough(createBufferedTransformStream())
}).pipeThrough(createBufferedTransformStream())
)
}
......@@ -866,10 +816,9 @@ export async function renderToHTML(
const initialTree = createFlightRouterStateFromLoaderTree(tree)
const initialStylesheets: string[] = getCSSInlinedLinkTags(
const initialStylesheets: string[] = getCssInlinedLinkTags(
ComponentMod,
serverComponentManifest,
dev
serverComponentManifest
)
const { Component: ComponentTree } = await createComponentTree({
......@@ -926,8 +875,7 @@ export async function renderToHTML(
transformStream: serverComponentsInlinedTransformStream,
serverComponentManifest,
serverContexts,
},
dev
}
)
const jsxStyleRegistry = createStyleRegistry()
......@@ -977,7 +925,6 @@ export async function renderToHTML(
}
return await continueFromInitialStream(renderStream, {
dev,
dataStream: serverComponentsInlinedTransformStream?.readable,
generateStaticHTML: generateStaticHTML || !hasConcurrentFeatures,
flushEffectHandler,
......
......@@ -171,14 +171,12 @@ export function renderToInitialStream({
export async function continueFromInitialStream(
renderStream: ReactReadableStream,
{
dev,
suffix,
dataStream,
generateStaticHTML,
flushEffectHandler,
initialStylesheets,
}: {
dev?: boolean
suffix?: string
dataStream?: ReadableStream<Uint8Array>
generateStaticHTML: boolean
......@@ -200,16 +198,9 @@ export async function continueFromInitialStream(
dataStream ? createInlineDataStream(dataStream) : null,
suffixUnclosed != null ? createSuffixStream(closeTag) : null,
createHeadInjectionTransformStream(
dev
? `<style data-next-hide-fouc>body{display:none}</style>
<noscript data-next-hide-fouc>
<style>body{display:block}</style>
</noscript>`
: initialStylesheets
? initialStylesheets
.map((href) => `<link rel="stylesheet" href="/_next/${href}">`)
.join('')
: ''
(initialStylesheets || [])
.map((href) => `<link rel="stylesheet" href="/_next/${href}">`)
.join('')
),
].filter(nonNullable)
......
import styles from './client-comp.module.css'
import { useEffect, useState } from 'react'
export default function ClientComp() {
......@@ -7,7 +9,7 @@ export default function ClientComp() {
}, [])
return (
<>
<p>Hello</p>
<p className={styles.client}>Hello</p>
{state.test}
</>
)
......
......@@ -5,6 +5,7 @@ export default function DashboardPage(props) {
<p id="from-dashboard" className="p">
hello from app/dashboard
</p>
<p className="bold">BOLD</p>
<p className="green">this is green</p>
<ClientComp />
</>
......
import '../styles/global.css'
export async function getServerSideProps() {
return {
props: {
......
.bold {
font-weight: bold;
}
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