Unverified Commit 6523a33f authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Enable turbopackFileSystemCacheForBuild by default (#96395)

### What?

Makes `experimental.turbopackFileSystemCacheForBuild` (Turbopack's
on-disk
filesystem cache for `next build`) enabled by default, matching the
dev-mode
flag. It stays disabled by default in non-Vercel CI environments, and
can
always be turned off explicitly with
`experimental.turbopackFileSystemCacheForBuild: false`.

### Why?

The build filesystem cache greatly speeds up warm builds, but was
previously
opt-in (only auto-enabled for canary builds on the Vercel builder).
Defaulting
it on gives everyone faster subsequent builds, while keeping it off in
non-Vercel CI where the cache is unlikely to persist between builds.

### How?

- `turbopackFileSystemCacheForBuildDefault()` now returns `true` except
when
  `isCI && !NOW_BUILDER` (removed the `isStableBuild()` gate).
- The explicit `false` opt-out already works via the existing
  `config.experimental?.turbopackFileSystemCacheForBuild || false` read.
- Adds an e2e test (`test/e2e/app-dir/turbopack-fs-cache-build-default`)
asserting `.next/cache/turbopack` is written by default, empty when the
flag
  is `false`, and empty in non-Vercel CI.
- Updates the `turbopackFileSystemCache` / Turbopack docs.

<!-- NEXT_JS_LLM -->

---------
Co-authored-by: 's avatarvercel-fleet[bot] <308483924+vercel-fleet[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 7612eaed
......@@ -8,16 +8,17 @@ description: Learn how to enable FileSystem Caching for Turbopack builds
Turbopack FileSystem Cache enables Turbopack to reduce work across `next dev` or `next build` commands. When enabled, Turbopack will save and restore data to the `.next` folder between builds, which can greatly speed up subsequent builds and dev sessions.
> **Good to know:** The FileSystem Cache feature is considered stable for development and experimental for production builds
> **Good to know:** The FileSystem Cache is **enabled by default** for `next dev`. It is enabled by default when running `next build` locally or on Vercel, where the cache is likely to persist between builds. You can explicitly enable or disable it with the flags below.
> **For deployment providers:** Other providers can enable the build cache by default on their platform by setting `experimental.turbopackFileSystemCacheForBuild: true` from their adapter's [`modifyConfig`](/docs/app/api-reference/adapters/creating-an-adapter) hook. Do this when your infrastructure preserves the `.next/cache` directory between builds, and only when the user has not set an explicit value for the flag.
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
// Enable filesystem caching for `next dev`
// Filesystem caching is enabled by default; set to `false` to disable it.
turbopackFileSystemCacheForDev: true,
// Enable filesystem caching for `next build`
turbopackFileSystemCacheForBuild: true,
},
}
......@@ -29,9 +30,8 @@ export default nextConfig
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
// Enable filesystem caching for `next dev`
// Filesystem caching is enabled by default; set to `false` to disable it.
turbopackFileSystemCacheForDev: true,
// Enable filesystem caching for `next build`
turbopackFileSystemCacheForBuild: true,
},
}
......@@ -41,8 +41,9 @@ module.exports = nextConfig
## Version Changes
| Version | Changes |
| --------- | -------------------------------------------------------------- |
| `v16.1.0` | FileSystem caching is enabled by default for development |
| `v16.0.0` | Beta release with separate flags for build and dev |
| `v15.5.0` | Persistent caching released as experimental on canary releases |
| Version | Changes |
| --------- | ------------------------------------------------------------------------------------ |
| `v16.3.0` | FileSystem caching is enabled by default for builds (depends on CI platform support) |
| `v16.1.0` | FileSystem caching is enabled by default for development |
| `v16.0.0` | Beta release with separate flags for build and dev |
| `v15.5.0` | Persistent caching released as experimental on canary releases |
......@@ -346,10 +346,12 @@ This can lead to subtle rendering differences when migrating from webpack to Tur
### Build Caching
Webpack supports [disk build caching](https://webpack.js.org/configuration/cache/#cache) to improve build performance. Turbopack provides a similar feature, currently in beta. Starting with Next 16, you can enable Turbopack’s filesystem cache by setting the following experimental flags:
Webpack supports [disk build caching](https://webpack.js.org/configuration/cache/#cache) to improve build performance. Turbopack provides a similar feature. Starting with Next 16, Turbopack's filesystem cache is controlled by the following experimental flags:
- [`experimental.turbopackFileSystemCacheForDev`](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) is enabled by default
- [`experimental.turbopackFileSystemCacheForBuild`](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) is currently opt-in
- [`experimental.turbopackFileSystemCacheForBuild`](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) is enabled by default for local builds and on Vercel, where the build cache is likely to persist.
Other deployment providers can enable the build cache by default on their platform by setting `experimental.turbopackFileSystemCacheForBuild: true` from their adapter's [`modifyConfig`](/docs/app/api-reference/adapters/creating-an-adapter) hook, when their infrastructure preserves the `.next/cache` directory between builds.
> **Good to know:** For this reason, when comparing webpack and Turbopack performance, make sure to delete the `.next` folder between builds to see a fair cold build comparison or enable the turbopack filesystem cache feature to compare warm builds.
......@@ -402,7 +404,7 @@ Additionally, the following experimental options are available under `experiment
| Option | Description | Default (dev) | Default (build) |
| ------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ----------------------------- |
| [`turbopackFileSystemCacheForDev`](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) | Enable filesystem cache for the dev server. | `true` | N/A |
| [`turbopackFileSystemCacheForBuild`](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) | Enable filesystem cache for builds. | N/A | `false` |
| [`turbopackFileSystemCacheForBuild`](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) | Enable filesystem cache for builds. | N/A | `true`<sup>1</sup> |
| `turbopackMinify` | Enable minification. | `false` | `true` |
| `turbopackSourceMaps` | Enable source maps. | `true` | `productionBrowserSourceMaps` |
| `turbopackInputSourceMaps` | Enable extraction of source maps from input files. | `true` | `true` |
......@@ -420,6 +422,10 @@ Additionally, the following experimental options are available under `experiment
| [`turbopackLocalPostcssConfig`](/docs/app/api-reference/config/next-config-js/turbopackLocalPostcssConfig) | Resolve `postcss.config.js` from the CSS file's directory first, then the project root. | `false` | `false` |
| `turbopackWorkerAssetPrefix` | Custom asset prefix for Web Worker URLs (entrypoint + module chunks), overriding `assetPrefix`. Mirrors webpack's `output.workerPublicPath`. | `undefined` | `undefined` |
<sup>1</sup> Enabled by default for local builds and on CI platforms (including
Vercel) where the build cache is likely to persist. Disabled by default on CI
platforms that have not yet opted into the feature.
```js filename="next.config.js"
module.exports = {
turbopack: {
......
......@@ -16,7 +16,6 @@ import { INFINITE_CACHE } from '../lib/constants'
import type { FallbackRouteParam } from '../build/static-paths/types'
import type { MemoryEvictionMode } from '../build/swc/types'
import type { CacheLife } from './use-cache/cache-life'
import { isStableBuild } from '../shared/lib/errors/canary-only-config-error'
import { isCI } from './ci-info'
/**
......@@ -2260,12 +2259,9 @@ export const defaultConfig = Object.freeze({
} satisfies NextConfig)
function turbopackFileSystemCacheForBuildDefault() {
if (isStableBuild()) return false
if (isCI && process.env.NOW_BUILDER) {
// Assume caching is available on vercel
return true
}
return false
// Disable in most CI environments, because we don't know if the cache will persist across builds.
// Providers: Override the default behavior using `modifyConfig` in your adapter.
return !isCI || Boolean(process.env.NOW_BUILDER)
}
export async function normalizeConfig(phase: string, config: any) {
......
import { nextTestSetup, isNextStart } from 'e2e-utils'
import fs from 'fs/promises'
import path from 'path'
// `experimental.turbopackFileSystemCacheForBuild` is enabled by default, except
// in CI environments that haven't opted in (`isCI && !NOW_BUILDER`), where the
// cache is unlikely to persist between builds. It can always be disabled
// explicitly with `turbopackFileSystemCacheForBuild: false`.
//
// This is a Turbopack + build (start) mode test. It runs `next build` with a
// controlled environment (the default depends on ambient `isCI`/`NOW_BUILDER`,
// and the test runner itself runs in CI) and checks whether anything is written
// to `.next/cache/turbopack`.
//
// `next/dist/compiled/ci-info` computes
// isCI = !!(CI || CONTINUOUS_INTEGRATION || BUILD_NUMBER || RUN_ID || <vendor>)
// so clearing those signals forces a non-CI environment, and setting `CI=1`
// (with `NOW_BUILDER` unset) forces a CI environment that hasn't opted in.
;(process.env.IS_TURBOPACK_TEST && isNextStart ? describe : describe.skip)(
'filesystem-cache build default',
() => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
// Simulate a non-CI (local) environment by clearing every CI signal that
// `ci-info` looks at.
const NON_CI_ENV = {
CI: '',
CONTINUOUS_INTEGRATION: '',
BUILD_NUMBER: '',
RUN_ID: '',
GITHUB_ACTIONS: '',
NOW_BUILDER: '',
// Persist even a tiny snapshot so the assertion doesn't depend on the
// minimum-compilation-time threshold.
TURBO_ENGINE_IGNORE_DIRTY: '1',
TURBO_ENGINE_SNAPSHOT_MIN_ACTIVE_TIME_MILLIS: '0',
}
function cachePath() {
return path.join(next.testDir, '.next', 'cache', 'turbopack')
}
async function getCacheSize(): Promise<number> {
let entries
try {
entries = await fs.readdir(cachePath(), {
recursive: true,
withFileTypes: true,
})
} catch {
// Directory doesn't exist -> nothing was cached.
return 0
}
let totalSize = 0
for (const entry of entries) {
if (entry.isFile()) {
const filePath = path.join(entry.parentPath ?? entry.path, entry.name)
totalSize += (await fs.stat(filePath)).size
}
}
return totalSize
}
async function cleanBuildOutput() {
await fs.rm(path.join(next.testDir, '.next'), {
recursive: true,
force: true,
})
}
// The shared fixture's next.config.js sets the flag explicitly from
// `ENABLE_CACHING`; overwrite it so we exercise the *default* instead.
async function setConfig(experimental: Record<string, unknown> = {}) {
await next.patchFile(
'next.config.js',
`module.exports = ${JSON.stringify({ experimental }, null, 2)}`
)
}
afterEach(async () => {
await setConfig()
})
it('writes the cache by default (no config, non-CI environment)', async () => {
await cleanBuildOutput()
await setConfig()
const { exitCode } = await next.build({ env: NON_CI_ENV })
expect(exitCode).toBe(0)
expect(await getCacheSize()).toBeGreaterThan(0)
})
it('writes nothing when turbopackFileSystemCacheForBuild is false', async () => {
await cleanBuildOutput()
await setConfig({ turbopackFileSystemCacheForBuild: false })
const { exitCode } = await next.build({ env: NON_CI_ENV })
expect(exitCode).toBe(0)
expect(await getCacheSize()).toBe(0)
})
it('writes nothing by default in CI that has not opted in', async () => {
await cleanBuildOutput()
await setConfig()
const { exitCode } = await next.build({
// Force a CI environment that hasn't opted in: `isCI` true, `NOW_BUILDER` unset.
env: { ...NON_CI_ENV, CI: '1' },
})
expect(exitCode).toBe(0)
expect(await getCacheSize()).toBe(0)
})
}
)
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