Unverified Commit eacb7490 authored by Cong-Cong Pan's avatar Cong-Cong Pan Committed by GitHub

chore: upgrade next-rspack to rspack 2.0 (#92222)

## Summary
- upgrade `@rspack/core` to `2.0.0-rc.0`
- sync the in-tree next rspack Rust binding/toolchain with newer rspack
releases
- align Next server runtime selection so `NEXT_RSPACK` uses the
turbo-like app runtime path
- include missing compiled `@next/react-refresh-utils` output in
`ncc-compiled`

## What is done
- `@next/rspack` Rust binding builds locally
- `packages/next` builds locally
- rspack-related tests are running and have been reduced to deeper
runtime compatibility failures

## Rspack test investigation
Latest checked CI run: `build-and-test` run `27129243230` at head
`484e7bf1b30655a9f94d0855b9e00774b4b38cd0`.

Confirmed Rspack / webpack parity gaps:
-
`test/e2e/edge-runtime-configurable-guards/edge-runtime-configurable-guards.test.ts`:
Rspack does not expose the webpack parser hooks used by
`MiddlewarePlugin`. The current Rspack path falls back to SWC analysis
in `finishModules`, which can report diagnostics but cannot apply the
parser-time transforms that wrap `eval` / `new Function`, track
`InnerGraph` usage for used vs unused dynamic code, or apply
`unstable_allowDynamic` with webpack parity. Dev therefore misses the
expected dynamic-code runtime warnings and also reports false
`process.cwd` Edge warnings from Next internals; prod fails
allowed/unused dynamic-code cases.
-
`test/development/middleware-overrides-node.js-api/middleware-overrides-node.js-api.test.ts`:
same parser-hook limitation. Webpack can observe that `process.cwd` is
overwritten before use, while the Rspack SWC fallback statically flags
`process.cwd` as an unsupported Edge Node API.
- `test/production/css-features/css-compilation.test.ts`: the CSS is
minified and prefixed as expected, but the Rspack lightningcss path
currently does not expose/control source map generation the way this
test expects, so emitted CSS has no `sourceMappingURL` comment or `.map`
file to assert.
- `test/e2e/app-dir/server-source-maps/server-source-maps.test.ts`:
invalid source maps are not handled with the same graceful diagnostic as
webpack/Node source-map handling. Rspack logs the raw `webpack-internal`
frame for the damaged map case instead of surfacing the expected
`Invalid source map. Only conformant source maps...` message with the
cause.
-
`test/e2e/app-dir/parallel-routes-revalidation/parallel-routes-revalidation.test.ts`:
raw CI output observed a dev-mode timeout waiting for `networkidle`
after refresh/back/forward lazy fetching. This was not the final
structured failure in the latest run, but it remains a Rspack dev parity
follow-up around router cache lazy fetches and network settling.
- `test/e2e/middleware-src/middleware-src.test.ts`: after the test adds
root middleware files, Rspack dev still lets `src/middleware`
participate; the expected behavior is that only the root middleware
runs.
- `test/e2e/env-config/env-config.test.ts`: changing `.env` logs `Reload
env:` but the client keeps the previous `NEXT_PUBLIC_` value, pointing
at an Rspack dev env invalidation/HMR gap.
-
`test/e2e/app-dir/use-cache-without-experimental-flag/use-cache-without-experimental-flag.test.ts`:
after enabling the `useCache` flag, the dev server does not finish
restarting, pointing at build-error recovery/restart parity.
-
`test/development/app-dir/server-navigation-error/server-navigation-error.test.ts`:
middleware navigation-error cases hit `ERR_CONNECTION_REFUSED`,
consistent with the Rspack dev server exiting or restarting unexpectedly
during those error flows.
- `test/e2e/opentelemetry/instrumentation/opentelemetry.test.ts`: the
custom-server dev process exits before the SDK handle is initialized,
then cleanup fails on `shutdown`; this needs follow-up in Rspack
dev/custom-server startup.
- `test/e2e/next-image-new/app-dir/app-dir.test.ts`: after toggling
image source, `onLoadingComplete` still reports the previous image
dimensions/source, pointing at an Rspack dev image/HMR or asset
invalidation parity issue.
- `test/e2e/node-cli-args/node-cli-args.test.ts`: on Node `20.19.x`,
`node --experimental-network-inspection` resolves instead of rejecting.
This looks like a Node-version behavior change rather than an Rspack
compiler issue.

Not attributed to this Rspack upgrade:
-
`test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts`
was marked by `scripts/pr-status.js` as a known flaky test across
branches.
-
`test/production/app-dir/build-output-prerender/build-output-prerender.test.ts`
ran in the webpack prod job and only differs by prerender error ordering
in the inline snapshot.


<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarBenjamin Woodruff <benjamin.woodruff@vercel.com>
parent 77f02f85
---
name: next-rspack
description: >
Maintain @next/rspack-core and @next/rspack-binding packages. Use when editing
rspack/package.json, rspack/crates/binding/Cargo.toml, rspack/rust-toolchain.toml,
or packages/next-rspack/package.json. Covers upgrading @rspack/core npm version,
rspack_* crate versions, Rust toolchain version, building and linking for local
testing, and NEXT_RSPACK environment variable usage. Does NOT apply to root
rust-toolchain.toml (that's for Turbopack).
---
# Next.js with Rspack
## When to Use
Use this skill when you need to:
- Upgrade `@rspack/core` npm package version
- Upgrade rspack crate dependency versions
- Upgrade Rust version in `rspack/rust-toolchain.toml` (rspack directory only)
- Fix Rspack-related compilation issues
- Develop Rspack-specific features in Next.js
> **⚠️ Scope Limitation**: This skill only applies to code and configuration under the `rspack/` directory. The `rust-toolchain.toml` in the repository root is for Turbopack and is outside the scope of this skill.
## Architecture Overview
### Package Structure
```
rspack/ # Independent workspace (separate rust toolchain and npm releases)
├── Cargo.toml # Rust workspace configuration
├── rust-toolchain.toml # Rust version configuration
├── package.json # @next/rspack-core package definition
├── lib/
│ ├── index.js # Exports @rspack/core + custom plugins
│ └── index.d.ts # Type definitions
└── crates/
└── binding/
├── Cargo.toml # Rust crate dependencies (rspack_* crates)
└── package.json # @next/rspack-binding package definition
packages/
└── next-rspack/
└── package.json # References @next/rspack-core
```
### Dependency Graph
```
packages/next-rspack
└── @next/rspack-core (rspack/package.json)
├── @rspack/core (npm dependency)
└── @next/rspack-binding (rspack/crates/binding)
└── rspack_* crates (Cargo.toml dependencies)
```
### Version Mapping Rules
| @rspack/core npm version | rspack crate version | Notes |
| ------------------------ | -------------------- | ------------------------------------------------- |
| `2.0.0-rc.0` | `0.100.0-rc.0` | npm major.minor maps to crate 0.(major\*50+minor) |
| `1.3.x` | `0.53.x` | e.g., 1.3 → 0.53 |
| `1.2.x` | `0.52.x` | e.g., 1.2 → 0.52 |
## Upgrade Process
### Step 1: Get Upstream Version Information
Query https://github.com/web-infra-dev/rspack to obtain:
- Target `@rspack/core` npm version
- Corresponding rspack crate version
- Rust channel version from `rust-toolchain.toml`
### Step 2: Update npm Dependencies
Edit `rspack/package.json`:
```json
{
"dependencies": {
"@rspack/core": "<new version>",
"@next/rspack-binding": "workspace:*"
}
}
```
### Step 3: Update Cargo.toml
Edit `rspack/crates/binding/Cargo.toml`, update all rspack crate versions:
```toml
[dependencies]
rspack_binding_builder = { version = "=<new crate version>" }
rspack_binding_builder_macros = { version = "=<new crate version>" }
rspack_core = { version = "=<new crate version>" }
rspack_error = { version = "=<new crate version>" }
rspack_hook = { version = "=<new crate version>" }
rspack_plugin_externals = { version = "=<new crate version>" }
rspack_regex = { version = "=<new crate version>" }
# rspack_sources version is managed separately, may not follow the main version
[target.'cfg(...)'.dependencies]
rspack_binding_builder = { version = "=<new crate version>", features = ["plugin"] }
[build-dependencies]
rspack_binding_build = { version = "=<new crate version>" }
```
### Step 4: Update Rust Toolchain
Edit `rspack/rust-toolchain.toml`:
```toml
[toolchain]
profile = "default"
components = ["rust-src"]
channel = "<nightly version matching upstream rspack>"
```
### Step 5: Verify Build
```bash
# Execute in rspack directory
cd rspack
# Check Rust code
cargo check
# Build binding (requires Rust installed)
pnpm build
```
### Step 6: Link to packages/next-rspack
`rspack/` is an independent workspace not included in the root pnpm-workspace, manual linking is required:
```bash
# Execute from repository root
cd packages/next-rspack
# Link locally built @next/rspack-core
pnpm link ../../rspack
```
Or modify `packages/next-rspack/package.json` to use local path (for local testing only, do not commit):
```json
{
"dependencies": {
"@next/rspack-core": "link:../../rspack"
}
}
```
> **Important**: After linking, run `pnpm install` in the root directory to update dependency relationships.
### Step 7: Run Tests
```bash
# Execute from repository root
pnpm test-rspack
```
## Key Files Checklist
Files to check/modify during upgrade:
| File Path | Modification |
| ------------------------------------ | ------------------------------------------------------------------------------------- |
| `rspack/package.json` | `@rspack/core` version, package version |
| `rspack/crates/binding/Cargo.toml` | rspack\_\* crate versions |
| `rspack/crates/binding/package.json` | binding package version |
| `rspack/rust-toolchain.toml` | Rust nightly version |
| `packages/next-rspack/package.json` | `@next/rspack-core` version reference (update on release, use link for local testing) |
## Pre-requisites for Local Testing
Before running `pnpm test-rspack`, you must build and link `@next/rspack-core`:
```bash
# 1. Build @next/rspack-core
cd rspack
pnpm install
pnpm build
# 2. Link to packages/next-rspack
cd ../packages/next-rspack
pnpm link ../../rspack
# 3. Return to root and update dependencies
cd ../..
pnpm install
# 4. Run tests
pnpm test-rspack
```
> **Note**: After modifying Rust code under `rspack/`, you need to re-run `pnpm build` from step 1.
## Test Commands
```bash
# Full test suite (using Rspack compiler)
pnpm test-rspack
# Development mode tests
pnpm test-dev-rspack
# Production mode tests
pnpm test-start-rspack
# Run specific tests only
pnpm run with-rspack pnpm testonly -- <test-pattern>
```
All test commands set environment variables via `with-rspack`:
```bash
cross-env NEXT_RSPACK=1 NEXT_TEST_USE_RSPACK=1
```
## Development Notes
### Environment Variable Differentiation
Use the `NEXT_RSPACK` environment variable to differentiate compilers in `packages/next/` code:
```typescript
// Check if using Rspack
const isRspack = Boolean(process.env.NEXT_RSPACK)
if (process.env.NEXT_RSPACK) {
// Rspack-specific logic
} else {
// Webpack logic
}
```
### Common Code Locations
- Compiler selection logic: `packages/next/src/lib/bundler.ts`
- Webpack configuration: `packages/next/src/build/webpack-config.ts`
- Loader adaptations: `packages/next/src/build/webpack/loaders/`
### Custom Plugins
`@next/rspack-core` exports = `@rspack/core` + custom plugins:
- `NextExternalsPlugin` - externals handling plugin implemented in Rust
## Release Process
Release via GitHub Actions workflow:
- Workflow: `.github/workflows/release-next-rspack.yml`
- Supports dry-run mode
- Supports multiple npm tags (latest, alpha, beta, canary)
## References
- Upstream Rspack repository: https://github.com/web-infra-dev/rspack
- Rspack documentation: https://rspack.rs
- Next.js with Rspack example: `examples/with-rspack/`
...@@ -457,6 +457,7 @@ jobs: ...@@ -457,6 +457,7 @@ jobs:
react: ['', '18.3.1'] react: ['', '18.3.1']
uses: ./.github/workflows/build_reusable.yml uses: ./.github/workflows/build_reusable.yml
with: with:
nodeVersion: 20.19.x
afterBuild: | afterBuild: |
export NEXT_EXTERNAL_TESTS_FILTERS="$(pwd)/test/rspack-dev-tests-manifest.json" export NEXT_EXTERNAL_TESTS_FILTERS="$(pwd)/test/rspack-dev-tests-manifest.json"
export NEXT_TEST_MODE=dev export NEXT_TEST_MODE=dev
...@@ -502,7 +503,7 @@ jobs: ...@@ -502,7 +503,7 @@ jobs:
react: ['', '18.3.1'] react: ['', '18.3.1']
uses: ./.github/workflows/build_reusable.yml uses: ./.github/workflows/build_reusable.yml
with: with:
nodeVersion: 20.9.0 nodeVersion: 20.19.x
afterBuild: | afterBuild: |
export NEXT_EXTERNAL_TESTS_FILTERS="$(pwd)/test/rspack-build-tests-manifest.json" export NEXT_EXTERNAL_TESTS_FILTERS="$(pwd)/test/rspack-build-tests-manifest.json"
export NEXT_TEST_MODE=start export NEXT_TEST_MODE=start
......
...@@ -36,6 +36,10 @@ on: ...@@ -36,6 +36,10 @@ on:
num_retries: num_retries:
type: number type: number
default: 2 default: 2
nodeVersion:
description: 'version of Node.js to use'
type: string
default: 20.9.0
jobs: jobs:
# First, build Next.js to execute across tests. # First, build Next.js to execute across tests.
...@@ -43,6 +47,7 @@ jobs: ...@@ -43,6 +47,7 @@ jobs:
name: build-next name: build-next
uses: ./.github/workflows/build_reusable.yml uses: ./.github/workflows/build_reusable.yml
with: with:
nodeVersion: ${{ inputs.nodeVersion }}
skipNativeBuild: yes skipNativeBuild: yes
stepName: build-next stepName: build-next
secrets: inherit secrets: inherit
...@@ -51,6 +56,7 @@ jobs: ...@@ -51,6 +56,7 @@ jobs:
name: build-native name: build-native
uses: ./.github/workflows/build_reusable.yml uses: ./.github/workflows/build_reusable.yml
with: with:
nodeVersion: ${{ inputs.nodeVersion }}
skipInstallBuild: yes skipInstallBuild: yes
stepName: build-native stepName: build-native
secrets: inherit secrets: inherit
...@@ -88,6 +94,7 @@ jobs: ...@@ -88,6 +94,7 @@ jobs:
group: ${{ fromJSON(needs.generate-matrices.outputs.e2e) }} group: ${{ fromJSON(needs.generate-matrices.outputs.e2e) }}
uses: ./.github/workflows/build_reusable.yml uses: ./.github/workflows/build_reusable.yml
with: with:
nodeVersion: ${{ inputs.nodeVersion }}
afterBuild: | afterBuild: |
# e2e and ${{ inputs.test_type }} tests with `node run-tests.js` # e2e and ${{ inputs.test_type }} tests with `node run-tests.js`
...@@ -119,7 +126,7 @@ jobs: ...@@ -119,7 +126,7 @@ jobs:
group: ${{ fromJSON(needs.generate-matrices.outputs.integration) }} group: ${{ fromJSON(needs.generate-matrices.outputs.integration) }}
uses: ./.github/workflows/build_reusable.yml uses: ./.github/workflows/build_reusable.yml
with: with:
nodeVersion: 20.9.0 nodeVersion: ${{ inputs.nodeVersion }}
afterBuild: | afterBuild: |
# legacy integration tests with `node run-tests.js` # legacy integration tests with `node run-tests.js`
......
...@@ -12,6 +12,7 @@ jobs: ...@@ -12,6 +12,7 @@ jobs:
uses: ./.github/workflows/integration_tests_reusable.yml uses: ./.github/workflows/integration_tests_reusable.yml
with: with:
name: rspack-production name: rspack-production
nodeVersion: 20.19.x
test_type: production test_type: production
run_before_test: | run_before_test: |
export NEXT_RSPACK=1 NEXT_TEST_USE_RSPACK=1 \ export NEXT_RSPACK=1 NEXT_TEST_USE_RSPACK=1 \
......
...@@ -12,6 +12,7 @@ jobs: ...@@ -12,6 +12,7 @@ jobs:
uses: ./.github/workflows/integration_tests_reusable.yml uses: ./.github/workflows/integration_tests_reusable.yml
with: with:
name: rspack-development name: rspack-development
nodeVersion: 20.19.x
test_type: development test_type: development
run_before_test: | run_before_test: |
export NEXT_RSPACK=1 NEXT_TEST_USE_RSPACK=1 export NEXT_RSPACK=1 NEXT_TEST_USE_RSPACK=1
......
...@@ -353,6 +353,7 @@ Use skills for conditional, deep workflows. Keep baseline iteration/build/test p ...@@ -353,6 +353,7 @@ Use skills for conditional, deep workflows. Keep baseline iteration/build/test p
- `$dce-edge` - DCE-safe `require()` patterns and edge/runtime constraints - `$dce-edge` - DCE-safe `require()` patterns and edge/runtime constraints
- `$react-vendoring` - `entry-base.ts` boundaries and vendored React type/runtime rules - `$react-vendoring` - `entry-base.ts` boundaries and vendored React type/runtime rules
- `$runtime-debug` - runtime-bundle/module-resolution regression reproduction and verification - `$runtime-debug` - runtime-bundle/module-resolution regression reproduction and verification
- `$next-rspack` - @next/rspack-core and @next/rspack-binding maintenance (rspack/ directory)
- `$authoring-skills` - how to create and maintain skills in `.agents/skills/` - `$authoring-skills` - how to create and maintain skills in `.agents/skills/`
## Context-Efficient Workflows ## Context-Efficient Workflows
......
...@@ -6,10 +6,10 @@ ...@@ -6,10 +6,10 @@
"directory": "packages/next-rspack" "directory": "packages/next-rspack"
}, },
"types": "index.d.ts", "types": "index.d.ts",
"dependencies": {
"@next/rspack-core": "1.0.2"
},
"scripts": { "scripts": {
"pack-for-isolated-tests": "pnpm pack --out ./packed.tgz" "pack-for-isolated-tests": "pnpm pack --out ./packed.tgz"
},
"dependencies": {
"@next/rspack-core": "1.0.3"
} }
} }
...@@ -189,7 +189,9 @@ module.exports = ({ dev, turbo, bundleType, experimental, ...rest }) => { ...@@ -189,7 +189,9 @@ module.exports = ({ dev, turbo, bundleType, experimental, ...rest }) => {
filename: `[name]${turbo ? '-turbo' : ''}${ filename: `[name]${turbo ? '-turbo' : ''}${
experimental ? '-experimental' : '' experimental ? '-experimental' : ''
}.runtime.${dev ? 'dev' : 'prod'}.js`, }.runtime.${dev ? 'dev' : 'prod'}.js`,
libraryTarget: 'commonjs2', library: {
type: 'commonjs2',
},
}, },
devtool: 'source-map', devtool: 'source-map',
optimization: optimization:
......
...@@ -294,24 +294,35 @@ export function hasExternalOtelApiPackage(): boolean { ...@@ -294,24 +294,35 @@ export function hasExternalOtelApiPackage(): boolean {
const UNSAFE_CACHE_REGEX = /[\\/]pages[\\/][^\\/]+(?:$|\?|#)/ const UNSAFE_CACHE_REGEX = /[\\/]pages[\\/][^\\/]+(?:$|\?|#)/
const NEGATIVE_UNSAFE_CACHE_REGEX = new RegExp( export const getCacheDirectories = process.env.NEXT_RSPACK
`^(?!.*${UNSAFE_CACHE_REGEX.source}).*$` ? (configs: webpack.Configuration[]) => {
) return new Set(
configs
export function getCacheDirectories( .map((cfg) => {
configs: webpack.Configuration[] const cache = cfg.cache as any
): Set<string> { if (typeof cache === 'object' && cache.type === 'persistent') {
return new Set( return cache.storage.directory
configs }
.map((cfg) => { return null
if (typeof cfg.cache === 'object' && cfg.cache.type === 'filesystem') { })
return cfg.cache.cacheDirectory .filter((dir): dir is string => dir != null)
} )
return null }
}) : (configs: webpack.Configuration[]) => {
.filter((dir) => dir != null) return new Set(
) configs
} .map((cfg) => {
if (
typeof cfg.cache === 'object' &&
cfg.cache.type === 'filesystem'
) {
return cfg.cache.cacheDirectory
}
return null
})
.filter((dir) => dir != null)
)
}
export default async function getBaseWebpackConfig( export default async function getBaseWebpackConfig(
dir: string, dir: string,
...@@ -380,6 +391,10 @@ export default async function getBaseWebpackConfig( ...@@ -380,6 +391,10 @@ export default async function getBaseWebpackConfig(
const isNodeServer = compilerType === COMPILER_NAMES.server const isNodeServer = compilerType === COMPILER_NAMES.server
const isRspack = Boolean(process.env.NEXT_RSPACK) const isRspack = Boolean(process.env.NEXT_RSPACK)
const CompleteRuntimePlugin = isRspack
? // @ts-ignore @next/rspack-core extends Rspack's core export with Next-only native plugins.
bundler.ForceCompleteRuntimePlugin
: ForceCompleteRuntimePlugin
const FlightClientEntryPlugin = const FlightClientEntryPlugin =
isRspack && process.env.BUILTIN_FLIGHT_CLIENT_ENTRY_PLUGIN isRspack && process.env.BUILTIN_FLIGHT_CLIENT_ENTRY_PLUGIN
...@@ -809,6 +824,12 @@ export default async function getBaseWebpackConfig( ...@@ -809,6 +824,12 @@ export default async function getBaseWebpackConfig(
: {}) as any), : {}) as any),
} }
// Resolve server-relative imports (e.g. `/styles/foo`) from the app
// directory. Webpack defaults this to `context`; Rspack needs it explicit.
if (isRspack) {
resolveConfig!.roots = [dir]
}
// Packages which will be split into the 'framework' chunk. // Packages which will be split into the 'framework' chunk.
// Only top-level packages are included, e.g. nested copies like // Only top-level packages are included, e.g. nested copies like
// 'node_modules/meow/node_modules/object-assign' are not included. // 'node_modules/meow/node_modules/object-assign' are not included.
...@@ -1322,8 +1343,10 @@ export default async function getBaseWebpackConfig( ...@@ -1322,8 +1343,10 @@ export default async function getBaseWebpackConfig(
: `static/chunks/${isDevFallback ? 'fallback/' : ''}[name]${ : `static/chunks/${isDevFallback ? 'fallback/' : ''}[name]${
dev ? '' : '-[contenthash]' dev ? '' : '-[contenthash]'
}.js`, }.js`,
library: isClient || isEdgeServer ? '_N_E' : undefined, library:
libraryTarget: isClient || isEdgeServer ? 'assign' : 'commonjs2', isClient || isEdgeServer
? { name: '_N_E', type: 'assign' }
: { type: 'commonjs2' },
hotUpdateChunkFilename: 'static/webpack/[id].[fullhash].hot-update.js', hotUpdateChunkFilename: 'static/webpack/[id].[fullhash].hot-update.js',
hotUpdateMainFilename: hotUpdateMainFilename:
'static/webpack/[fullhash].[runtime].hot-update.json', 'static/webpack/[fullhash].[runtime].hot-update.json',
...@@ -1989,9 +2012,7 @@ export default async function getBaseWebpackConfig( ...@@ -1989,9 +2012,7 @@ export default async function getBaseWebpackConfig(
plugins: [ plugins: [
// In prod Webpack will already have a runtime for all reachable chunks. // In prod Webpack will already have a runtime for all reachable chunks.
// During dev, it will update the runtime as chunks come in which may be too late for Flight. // During dev, it will update the runtime as chunks come in which may be too late for Flight.
// dev && new CompleteRuntimePlugin(),
// TODO: Rspack currently does not support the hooks and chunk methods required by ForceCompleteRuntimePlugin.
dev && !isRspack && new ForceCompleteRuntimePlugin(),
// Handle deferred entries - must be added early to intercept entry processing // Handle deferred entries - must be added early to intercept entry processing
!isRspack && !isRspack &&
config.experimental.deferredEntries?.length && config.experimental.deferredEntries?.length &&
...@@ -2452,16 +2473,16 @@ export default async function getBaseWebpackConfig( ...@@ -2452,16 +2473,16 @@ export default async function getBaseWebpackConfig(
buildDependencies.push(jsConfigPath) buildDependencies.push(jsConfigPath)
} }
// @ts-ignore const rspackCacheKey = `${compilerType}${isDevFallback ? '-fallback' : ''}`
webpack5Config.experiments.cache = { webpack5Config.cache = {
type: 'persistent', type: 'persistent',
buildDependencies, buildDependencies,
storage: { storage: {
type: 'filesystem', type: 'filesystem',
directory: cache.cacheDirectory, directory: path.join(distDir, 'cache', 'rspack', rspackCacheKey),
}, },
version: `${__dirname}|${process.env.__NEXT_VERSION}|${configVars}`, version: `${__dirname}|${process.env.__NEXT_VERSION}|${configVars}|${rspackCacheKey}`,
} } as any
} }
if (process.env.NEXT_WEBPACK_LOGGING) { if (process.env.NEXT_WEBPACK_LOGGING) {
...@@ -2548,29 +2569,20 @@ export default async function getBaseWebpackConfig( ...@@ -2548,29 +2569,20 @@ export default async function getBaseWebpackConfig(
deploymentId: config.deploymentId, deploymentId: config.deploymentId,
}) })
// @ts-ignore Cache exists if (!isRspack) {
webpackConfig.cache.name = `${webpackConfig.name}-${webpackConfig.mode}${ // @ts-ignore Cache exists
isDevFallback ? '-fallback' : '' webpackConfig.cache.name = `${webpackConfig.name}-${webpackConfig.mode}${
}` isDevFallback ? '-fallback' : ''
}`
}
if (dev) { if (dev && !isRspack) {
if (webpackConfig.module) { if (webpackConfig.module) {
if (isRspack) { webpackConfig.module.unsafeCache = (module: any) =>
;(webpackConfig.module.unsafeCache as any) = NEGATIVE_UNSAFE_CACHE_REGEX !UNSAFE_CACHE_REGEX.test(module.resource)
} else {
webpackConfig.module.unsafeCache = (module: any) =>
!UNSAFE_CACHE_REGEX.test(module.resource)
}
} else { } else {
if (isRspack) { webpackConfig.module = {
;(webpackConfig.module as any) = { unsafeCache: (module: any) => !UNSAFE_CACHE_REGEX.test(module.resource),
unsafeCache: NEGATIVE_UNSAFE_CACHE_REGEX,
}
} else {
webpackConfig.module = {
unsafeCache: (module: any) =>
!UNSAFE_CACHE_REGEX.test(module.resource),
}
} }
} }
} }
...@@ -2636,6 +2648,24 @@ export default async function getBaseWebpackConfig( ...@@ -2636,6 +2648,24 @@ export default async function getBaseWebpackConfig(
) )
} }
} }
if (isRspack && 'CI' in process.env) {
// Rspack enables stats colors by default in CI, which can leak ANSI reset
// codes into error messages. Keep explicit user stats.colors unchanged.
const { stats } = webpackConfig
if (stats === undefined) {
webpackConfig.stats = { colors: false }
} else if (
stats &&
typeof stats === 'object' &&
!Array.isArray(stats) &&
stats.colors === undefined
) {
stats.colors = false
}
}
const rules = webpackConfig.module?.rules || [] const rules = webpackConfig.module?.rules || []
const customSvgRule = rules.find( const customSvgRule = rules.find(
......
...@@ -160,7 +160,10 @@ export class ReplayableNodeStream { ...@@ -160,7 +160,10 @@ export class ReplayableNodeStream {
'Node.js Readable cannot be teed in the edge runtime' 'Node.js Readable cannot be teed in the edge runtime'
) )
} else { } else {
if (process.env.__NEXT_BUNDLER === 'Webpack') { if (
process.env.__NEXT_BUNDLER === 'Webpack' ||
process.env.__NEXT_BUNDLER === 'Rspack'
) {
ReadableCtor = ( ReadableCtor = (
__non_webpack_require__('node:stream') as typeof import('node:stream') __non_webpack_require__('node:stream') as typeof import('node:stream')
).Readable ).Readable
......
...@@ -623,11 +623,16 @@ function createServer( ...@@ -623,11 +623,16 @@ function createServer(
(options.turbo || options.turbopack || process.env.IS_TURBOPACK_TEST) (options.turbo || options.turbopack || process.env.IS_TURBOPACK_TEST)
const selectWebpack = const selectWebpack =
options && (options.webpack || process.env.IS_WEBPACK_TEST) options && (options.webpack || process.env.IS_WEBPACK_TEST)
if (selectTurbopack && selectWebpack) { // Rspack is selected through env/config side effects instead of a custom
// server option, so don't fall back to the default Turbopack auto mode.
const selectRspack = !!process.env.NEXT_RSPACK
if (selectTurbopack && selectWebpack && selectRspack) {
throw new Error('Pass either `webpack` or `turbopack`, not both.') throw new Error('Pass either `webpack` or `turbopack`, not both.')
} }
if (selectTurbopack || !selectWebpack) { if (selectTurbopack) {
process.env.TURBOPACK ??= selectTurbopack ? '1' : 'auto' process.env.TURBOPACK ??= '1'
} else if (!selectWebpack && !selectRspack) {
process.env.TURBOPACK ??= 'auto'
} }
} else { } else {
if (options && (options.webpack || options.turbo || options.turbopack)) { if (options && (options.webpack || options.turbo || options.turbopack)) {
......
...@@ -141,7 +141,10 @@ function webToReadable( ...@@ -141,7 +141,10 @@ function webToReadable(
if (process.env.TURBOPACK) { if (process.env.TURBOPACK) {
Readable = (require('node:stream') as typeof import('node:stream')) Readable = (require('node:stream') as typeof import('node:stream'))
.Readable .Readable
} else if (process.env.__NEXT_BUNDLER === 'Webpack') { } else if (
process.env.__NEXT_BUNDLER === 'Webpack' ||
process.env.__NEXT_BUNDLER === 'Rspack'
) {
Readable = ( Readable = (
__non_webpack_require__('node:stream') as typeof import('node:stream') __non_webpack_require__('node:stream') as typeof import('node:stream')
).Readable ).Readable
...@@ -175,7 +178,10 @@ export async function streamToUint8Array(stream: AnyStream) { ...@@ -175,7 +178,10 @@ export async function streamToUint8Array(stream: AnyStream) {
if (process.env.TURBOPACK) { if (process.env.TURBOPACK) {
Readable = (require('node:stream') as typeof import('node:stream')) Readable = (require('node:stream') as typeof import('node:stream'))
.Readable .Readable
} else if (process.env.__NEXT_BUNDLER === 'Webpack') { } else if (
process.env.__NEXT_BUNDLER === 'Webpack' ||
process.env.__NEXT_BUNDLER === 'Rspack'
) {
Readable = ( Readable = (
__non_webpack_require__('node:stream') as typeof import('node:stream') __non_webpack_require__('node:stream') as typeof import('node:stream')
).Readable ).Readable
......
...@@ -44,7 +44,7 @@ function formatMessage( ...@@ -44,7 +44,7 @@ function formatMessage(
) { ) {
// TODO: Replace this once webpack 5 is stable // TODO: Replace this once webpack 5 is stable
if (typeof message === 'object' && message.message) { if (typeof message === 'object' && message.message) {
const filteredModuleTrace = let filteredModuleTrace =
message.moduleTrace && message.moduleTrace &&
message.moduleTrace.filter( message.moduleTrace.filter(
(trace: any) => (trace: any) =>
......
This diff is collapsed.
...@@ -500,7 +500,7 @@ describe('ReactRefreshLogBox app', () => { ...@@ -500,7 +500,7 @@ describe('ReactRefreshLogBox app', () => {
"source": "./index.module.css "source": "./index.module.css
╰─▶ × SyntaxError ╰─▶ × SyntaxError
│ │
│ (1:1) <FIXME-project-root>/index.module.css Unknown word │ (1:1) <FIXME-project-root>/index.module.css Unknown word .button
│ │
│ > 1 | .button │ > 1 | .button
│ | ^ │ | ^
......
...@@ -171,7 +171,10 @@ describe('Error overlay - editor links', () => { ...@@ -171,7 +171,10 @@ describe('Error overlay - editor links', () => {
await session.waitForRedbox() await session.waitForRedbox()
await clickImportTraceFiles(browser) await clickImportTraceFiles(browser)
await check(() => editorRequestsCount, /3/) await check(
() => editorRequestsCount,
process.env.NEXT_RSPACK ? /4/ : /3/
)
}) })
} }
) )
......
...@@ -4,7 +4,7 @@ import { createSandbox } from 'development-sandbox' ...@@ -4,7 +4,7 @@ import { createSandbox } from 'development-sandbox'
import { outdent } from 'outdent' import { outdent } from 'outdent'
describe('Error overlay - RSC build errors', () => { describe('Error overlay - RSC build errors', () => {
const { next, isTurbopack } = nextTestSetup({ const { next, isTurbopack, isRspack } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'rsc-build-errors')), files: new FileRef(path.join(__dirname, 'fixtures', 'rsc-build-errors')),
skipStart: true, skipStart: true,
}) })
...@@ -383,6 +383,10 @@ describe('Error overlay - RSC build errors', () => { ...@@ -383,6 +383,10 @@ describe('Error overlay - RSC build errors', () => {
expect(await session.getRedboxSource()).toInclude( expect(await session.getRedboxSource()).toInclude(
`Export whatever doesn't exist in target module` `Export whatever doesn't exist in target module`
) )
} else if (isRspack) {
expect(await session.getRedboxDescription()).toInclude(
`'whatever' is not exported from 'next/root-params'`
)
} else { } else {
expect(await session.getRedboxDescription()).toInclude( expect(await session.getRedboxDescription()).toInclude(
`whatever) is not a function` `whatever) is not a function`
......
...@@ -731,7 +731,7 @@ describe('ReactRefreshLogBox', () => { ...@@ -731,7 +731,7 @@ describe('ReactRefreshLogBox', () => {
"source": "./index.module.css "source": "./index.module.css
╰─▶ × SyntaxError ╰─▶ × SyntaxError
│ │
│ (1:1) <FIXME-project-root>/index.module.css Unknown word │ (1:1) <FIXME-project-root>/index.module.css Unknown word .button
│ │
│ > 1 | .button │ > 1 | .button
│ | ^ │ | ^
......
...@@ -4,7 +4,7 @@ import { retry } from 'next-test-utils' ...@@ -4,7 +4,7 @@ import { retry } from 'next-test-utils'
const cacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true' const cacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true'
describe('dev-output', () => { describe('dev-output', () => {
const { next, isTurbopack } = nextTestSetup({ const { next, isTurbopack, isRspack } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
...@@ -18,6 +18,10 @@ describe('dev-output', () => { ...@@ -18,6 +18,10 @@ describe('dev-output', () => {
expect(output).toContain('Next.js') expect(output).toContain('Next.js')
expect(output).toContain('Turbopack') expect(output).toContain('Turbopack')
expect(output).toContain('Cache Components') expect(output).toContain('Cache Components')
} else if (isRspack) {
expect(output).toContain('Next.js')
expect(output).toContain('Rspack')
expect(output).toContain('Cache Components')
} else { } else {
expect(output).toContain('Next.js') expect(output).toContain('Next.js')
expect(output).toContain('webpack') expect(output).toContain('webpack')
...@@ -28,6 +32,8 @@ describe('dev-output', () => { ...@@ -28,6 +32,8 @@ describe('dev-output', () => {
expect(output).toContain('Next.js') expect(output).toContain('Next.js')
if (isTurbopack) { if (isTurbopack) {
expect(output).toContain('Turbopack') expect(output).toContain('Turbopack')
} else if (isRspack) {
expect(output).toContain('Rspack')
} else { } else {
expect(output).toContain('webpack') expect(output).toContain('webpack')
} }
......
import { Html, Head, Main, NextScript } from 'next/document' import { Html, Head, Main, NextScript } from 'next/document'
import { Abel } from 'next/font/google' import { Abel } from 'next/font/google'
// eslint-disable-next-line no-unused-vars
const abel = Abel({ weight: '400' }) const abel = Abel({ weight: '400' })
export default function Document() { export default function Document() {
return ( return (
<Html> <Html>
<Head /> <Head />
<body> <body className={abel.variable}>
<Main /> <Main />
<NextScript /> <NextScript />
</body> </body>
......
...@@ -678,11 +678,9 @@ describe('app-dir - server source maps', () => { ...@@ -678,11 +678,9 @@ describe('app-dir - server source maps', () => {
"eval app/module-evaluation/module.js (1:22)", "eval app/module-evaluation/module.js (1:22)",
"<FIXME-file-protocol>", "<FIXME-file-protocol>",
"<FIXME-file-protocol>", "<FIXME-file-protocol>",
"eval about:/Prerender/webpack-internal:///(rsc)/app/module-evaluation/page.js (5:60)", "eval about:/Prerender/webpack-internal:///(rsc)/app/module-evaluation/page.js (5:45)",
"<FIXME-file-protocol>", "<FIXME-file-protocol>",
"<FIXME-file-protocol>", "<FIXME-file-protocol>",
"Function.all <anonymous>",
"Function.all <anonymous>",
"Page <anonymous>", "Page <anonymous>",
], ],
} }
......
import { nextTestSetup, isNextDev, isNextStart } from 'e2e-utils' import { nextTestSetup, isNextDev, isNextStart, isRspack } from 'e2e-utils'
import { retry } from 'next-test-utils' import { retry } from 'next-test-utils'
import stripAnsi from 'next/dist/compiled/strip-ansi' import stripAnsi from 'next/dist/compiled/strip-ansi'
...@@ -146,6 +146,8 @@ describe.each([ ...@@ -146,6 +146,8 @@ describe.each([
if (isTurbopack) { if (isTurbopack) {
expect(cliOutput).toContain(`Ecmascript file had an error`) expect(cliOutput).toContain(`Ecmascript file had an error`)
} else if (isRspack) {
expect(cliOutput).toContain(`Failed to compile`)
} else { } else {
expect(cliOutput).toContain(`Failed to compile`) expect(cliOutput).toContain(`Failed to compile`)
expect(cliOutput).toContain(`Used by usingEval, usingEvalSync`) expect(cliOutput).toContain(`Used by usingEval, usingEvalSync`)
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
// import.meta.glob is a Turbopack-only feature; skip under webpack // import.meta.glob is a Turbopack-only feature; skip under webpack
const testFn = process.env.IS_WEBPACK_TEST ? describe.skip : describe const testFn =
process.env.IS_WEBPACK_TEST || process.env.NEXT_RSPACK
? describe.skip
: describe
testFn('import-meta-glob', () => { testFn('import-meta-glob', () => {
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
......
...@@ -8,7 +8,7 @@ import { ...@@ -8,7 +8,7 @@ import {
import cheerio from 'cheerio' import cheerio from 'cheerio'
describe('Build Error Tests', () => { describe('Build Error Tests', () => {
const { next, isTurbopack, isNextDeploy } = nextTestSetup({ const { next, isTurbopack, isRspack, isNextDeploy } = nextTestSetup({
files: __dirname, files: __dirname,
skipStart: true, skipStart: true,
skipDeployment: true, skipDeployment: true,
...@@ -34,7 +34,9 @@ describe('Build Error Tests', () => { ...@@ -34,7 +34,9 @@ describe('Build Error Tests', () => {
} else { } else {
expect(cliOutput).toContain('./pages/static-img.js') expect(cliOutput).toContain('./pages/static-img.js')
} }
expect(cliOutput).not.toContain('Import trace for requested module') if (!isRspack) {
expect(cliOutput).not.toContain('Import trace for requested module')
}
} }
) )
} }
......
...@@ -8,7 +8,7 @@ import cheerio from 'cheerio' ...@@ -8,7 +8,7 @@ import cheerio from 'cheerio'
;(process.env.__NEXT_CACHE_COMPONENTS === 'true' ? describe.skip : describe)( ;(process.env.__NEXT_CACHE_COMPONENTS === 'true' ? describe.skip : describe)(
'Build Error Tests', 'Build Error Tests',
() => { () => {
const { next, isTurbopack } = nextTestSetup({ const { next, isTurbopack, isRspack } = nextTestSetup({
files: __dirname, files: __dirname,
skipStart: true, skipStart: true,
skipDeployment: true, skipDeployment: true,
...@@ -37,7 +37,9 @@ import cheerio from 'cheerio' ...@@ -37,7 +37,9 @@ import cheerio from 'cheerio'
} else { } else {
expect(cliOutput).toContain('./app/static-img/page.js') expect(cliOutput).toContain('./app/static-img/page.js')
} }
expect(cliOutput).not.toContain('Import trace for requested module') if (!isRspack) {
expect(cliOutput).not.toContain('Import trace for requested module')
}
} }
) )
}) })
......
...@@ -2,7 +2,7 @@ import { nextTestSetup, isNextDev, type Playwright } from 'e2e-utils' ...@@ -2,7 +2,7 @@ import { nextTestSetup, isNextDev, type Playwright } from 'e2e-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
describe('Build Error Tests', () => { describe('Build Error Tests', () => {
const { next, isTurbopack, isNextDeploy } = nextTestSetup({ const { next, isTurbopack, isRspack, isNextDeploy } = nextTestSetup({
files: __dirname, files: __dirname,
skipStart: true, skipStart: true,
skipDeployment: true, skipDeployment: true,
...@@ -32,7 +32,9 @@ describe('Build Error Tests', () => { ...@@ -32,7 +32,9 @@ describe('Build Error Tests', () => {
} else { } else {
expect(cliOutput).toContain('./pages/static-img.js') expect(cliOutput).toContain('./pages/static-img.js')
} }
expect(cliOutput).not.toContain('Import trace for requested module') if (!isRspack) {
expect(cliOutput).not.toContain('Import trace for requested module')
}
} }
) )
}) })
......
...@@ -2,7 +2,7 @@ import { nextTestSetup, isNextDev, type Playwright } from 'e2e-utils' ...@@ -2,7 +2,7 @@ import { nextTestSetup, isNextDev, type Playwright } from 'e2e-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
describe('Build Error Tests', () => { describe('Build Error Tests', () => {
const { next, isNextDeploy } = nextTestSetup({ const { next, isNextDeploy, isRspack } = nextTestSetup({
files: __dirname, files: __dirname,
skipStart: true, skipStart: true,
skipDeployment: true, skipDeployment: true,
...@@ -29,7 +29,9 @@ describe('Build Error Tests', () => { ...@@ -29,7 +29,9 @@ describe('Build Error Tests', () => {
"Module not found: Can't resolve '../public/foo/test-rect-broken.jpg" "Module not found: Can't resolve '../public/foo/test-rect-broken.jpg"
) )
expect(cliOutput).toContain('pages/static-img.js') expect(cliOutput).toContain('pages/static-img.js')
expect(cliOutput).not.toContain('Import trace for requested module') if (!isRspack) {
expect(cliOutput).not.toContain('Import trace for requested module')
}
} }
) )
}) })
......
...@@ -5,7 +5,7 @@ import { nextTestSetup } from 'e2e-utils' ...@@ -5,7 +5,7 @@ import { nextTestSetup } from 'e2e-utils'
import { findPort, killApp, renderViaHTTP, retry } from 'next-test-utils' import { findPort, killApp, renderViaHTTP, retry } from 'next-test-utils'
describe('page features telemetry', () => { describe('page features telemetry', () => {
const { next, isTurbopack, isNextStart, skipped } = nextTestSetup({ const { next, isTurbopack, isRspack, isNextStart, skipped } = nextTestSetup({
files: __dirname, files: __dirname,
skipStart: true, skipStart: true,
// Calls `next.build()` directly which is not supported on `NextDeployInstance`. // Calls `next.build()` directly which is not supported on `NextDeployInstance`.
...@@ -135,6 +135,9 @@ describe('page features telemetry', () => { ...@@ -135,6 +135,9 @@ describe('page features telemetry', () => {
} else { } else {
it('detects correctly for `next dev` stopped (no turbo)', async () => { it('detects correctly for `next dev` stopped (no turbo)', async () => {
const port = await findPort() const port = await findPort()
// Rspack startup can take longer while restoring persistent cache state,
// so give telemetry events a wider retry window.
const retryDuration = isRspack ? 10_000 : 3_000
let stderr = '' let stderr = ''
const { child, exit } = await launchDevServer(port, { const { child, exit } = await launchDevServer(port, {
...@@ -148,7 +151,7 @@ describe('page features telemetry', () => { ...@@ -148,7 +151,7 @@ describe('page features telemetry', () => {
await retry(async () => { await retry(async () => {
expect(stderr).toMatch(/NEXT_CLI_SESSION_STARTED/) expect(stderr).toMatch(/NEXT_CLI_SESSION_STARTED/)
}) }, retryDuration)
await renderViaHTTP(port, '/hello') await renderViaHTTP(port, '/hello')
if (child) { if (child) {
...@@ -158,7 +161,7 @@ describe('page features telemetry', () => { ...@@ -158,7 +161,7 @@ describe('page features telemetry', () => {
await retry(async () => { await retry(async () => {
expect(stderr).toMatch(/NEXT_CLI_SESSION_STOPPED/) expect(stderr).toMatch(/NEXT_CLI_SESSION_STOPPED/)
}) }, retryDuration)
expect(stderr).toContain('NEXT_CLI_SESSION_STOPPED') expect(stderr).toContain('NEXT_CLI_SESSION_STOPPED')
const event1 = /NEXT_CLI_SESSION_STOPPED[\s\S]+?{([\s\S]+?)}/ const event1 = /NEXT_CLI_SESSION_STOPPED[\s\S]+?{([\s\S]+?)}/
......
...@@ -2,7 +2,7 @@ import { isNextDeploy, nextTestSetup } from 'e2e-utils' ...@@ -2,7 +2,7 @@ import { isNextDeploy, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { retry } from 'next-test-utils'
// `experimental.turbopackWorkerAssetPrefix` is turbopack-only. // `experimental.turbopackWorkerAssetPrefix` is turbopack-only.
const isTurbopack = !process.env.IS_WEBPACK_TEST const isTurbopack = !process.env.IS_WEBPACK_TEST && !process.env.NEXT_RSPACK
const describeTurbopack = const describeTurbopack =
isTurbopack && !isNextDeploy ? describe : describe.skip isTurbopack && !isNextDeploy ? describe : describe.skip
......
...@@ -3,6 +3,7 @@ module.exports = { ...@@ -3,6 +3,7 @@ module.exports = {
urlImports: [ urlImports: [
'http://localhost:12345/', 'http://localhost:12345/',
'https://github.com/vercel/next.js/raw/canary/', 'https://github.com/vercel/next.js/raw/canary/',
'https://raw.githubusercontent.com/vercel/next.js/canary/',
], ],
}, },
} }
...@@ -7,6 +7,11 @@ module.exports = { ...@@ -7,6 +7,11 @@ module.exports = {
new BundleAnalyzerPlugin({ new BundleAnalyzerPlugin({
analyzerMode: 'disabled', analyzerMode: 'disabled',
generateStatsFile: true, generateStatsFile: true,
statsOptions: {
chunks: true,
chunkModules: true,
modules: true,
},
}) })
) )
return config return config
......
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