Unverified Commit 0bb7b8a2 authored by Sam Poder's avatar Sam Poder Committed by GitHub

[turbopack] Add e2e test that uses component chunks + workers (#96556)

Follow up to the bug that was fixed in
https://github.com/vercel/next.js/pull/96432.
parent 10dc5fd5
export default function AppLayout({ children }) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}
'use client'
import { payload as bothPagesPayload } from '../../lib/shared-with-both-pages'
import { payload as onePagePayload } from '../../lib/shared-with-one-page'
// This page shares both heavy modules with the worker, `/page-b` only shares one
// of them. The differing sets of chunk groups are what make Turbopack merge the
// two modules into a single chunk with two component chunks.
export default function PageA() {
return (
<div>
<p id="both-pages">{bothPagesPayload.length}</p>
<p id="one-page">{onePagePayload.length}</p>
</div>
)
}
'use client'
import { payload as bothPagesPayload } from '../../lib/shared-with-both-pages'
export default function PageB() {
return (
<div>
<p id="both-pages">{bothPagesPayload.length}</p>
</div>
)
}
'use client'
import { useState } from 'react'
export default function Home() {
const [state, setState] = useState('default')
return (
<div>
<button
onClick={() => {
const worker = new Worker(new URL('./worker.js', import.meta.url))
worker.addEventListener('message', (event) => {
setState(event.data)
})
}}
>
Get web worker data
</button>
<p>Worker state: </p>
<p id="worker-state">{state}</p>
</div>
)
}
import {
marker as bothPagesMarker,
payload as bothPagesPayload,
} from '../lib/shared-with-both-pages'
import {
marker as onePageMarker,
payload as onePagePayload,
} from '../lib/shared-with-one-page'
// Reading the payloads keeps the filler in both modules alive.
self.postMessage(
`${bothPagesMarker}:${bothPagesPayload.length}|${onePageMarker}:${onePagePayload.length}`
)
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
turbopackChunking: {
generateComponentChunks: true,
// The defaults (50 KB / 20 KB) would require much bigger fixture modules. These
// thresholds keep the generated `lib/shared-with-*.js` modules (see
// `sharedModule()` in the test file) small while still being big enough to each
// become a component chunk of the chunk they get merged into.
minChunkSize: 8000,
minComponentChunkSize: 1000,
},
},
}
module.exports = nextConfig
import { FileRef, isNextStart, nextTestSetup } from 'e2e-utils'
import { retry, shouldUseTurbopack } from 'next-test-utils'
import fs from 'fs/promises'
import path from 'path'
import { promisify } from 'util'
import globOrig from 'glob'
const glob = promisify(globOrig)
/**
* Builds one of the two modules that the worker shares with the pages. Each of them
* has to be big enough to become a component chunk on its own
* (`minComponentChunkSize`) but small enough to be merged with the other one
* (`minChunkSize`), and together they have to exceed `minChunkSize` — see
* next.config.js for those thresholds. Only the size of the filler matters, so it is
* generated here instead of being checked in.
*/
function sharedModule(marker: string): string {
const filler: string[] = []
for (let bytes = 0, i = 0; bytes < 5600; i++) {
const entry = `${marker}-filler-${i}-${'0123456789abcdefghijklmnopqrstuvwxyz'.repeat(2)}`
filler.push(entry)
bytes += entry.length
}
return `export const marker = ${JSON.stringify(marker)}
export const payload = ${JSON.stringify(filler)}.join('|')
`
}
// Component chunks are only emitted by Turbopack's production chunking, so there is
// nothing to cover in development or with webpack.
;(shouldUseTurbopack() && isNextStart ? describe : describe.skip)(
'app dir - worker with component chunks',
() => {
const { next } = nextTestSetup({
files: {
app: new FileRef(path.join(__dirname, 'app')),
'next.config.js': new FileRef(path.join(__dirname, 'next.config.js')),
'lib/shared-with-both-pages.js': sharedModule('both-pages'),
'lib/shared-with-one-page.js': sharedModule('one-page'),
},
})
it('should pass a merged chunk to the worker', async () => {
const staticDir = path.join(next.testDir, '.next/static')
const chunkPaths = await glob('**/chunks/**/*.js', {
cwd: staticDir,
nodir: true,
})
const chunks = await Promise.all(
chunkPaths.map((chunkPath) =>
fs.readFile(path.join(staticDir, chunkPath), 'utf8')
)
)
// The generated worker loader calls `createWorker` with the worker entrypoint
// followed by the worker's chunk list. A merged chunk is passed as an object
// (`{ path, moduleChunks }`) rather than a plain path string, which is the case
// this fixture exists to cover: `lib/shared-with-both-pages.js` and
// `lib/shared-with-one-page.js` are reachable from different sets of pages, so
// they get merged into one chunk that is then split into two component chunks.
const chunkLists = chunks.flatMap((content) => {
const matches = content.matchAll(/turbopack-worker-[^"]+\.js",/g)
// The chunk list follows the entrypoint, well within the next 500 characters.
return Array.from(matches, (match) =>
content.slice(match.index, match.index + 500)
)
})
expect(chunkLists).not.toHaveLength(0)
expect(
chunkLists.some((chunkList) => chunkList.includes('moduleChunks'))
).toBe(true)
})
it('should support a web worker whose chunks include a merged chunk', async () => {
const browser = await next.browser('/')
expect(await browser.elementByCss('#worker-state').text()).toBe('default')
await browser.elementByCss('button').click()
await retry(async () =>
expect(await browser.elementByCss('#worker-state').text()).toMatch(
/^both-pages:\d+\|one-page:\d+$/
)
)
})
it('should render the pages that share modules with the worker', async () => {
const pageA = await next.browser('/page-a')
expect(await pageA.elementByCss('#both-pages').text()).toMatch(/^\d+$/)
expect(await pageA.elementByCss('#one-page').text()).toMatch(/^\d+$/)
const pageB = await next.browser('/page-b')
expect(await pageB.elementByCss('#both-pages').text()).toMatch(/^\d+$/)
})
}
)
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