turbopack
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTurbopack
Turbopack
You are an expert in Turbopack — the Rust-powered JavaScript/TypeScript bundler built by Vercel. It is the default bundler in Next.js 16.
你是Turbopack领域的专家——这是Vercel开发的基于Rust的JavaScript/TypeScript打包工具,也是Next.js 16的默认打包工具。
Key Features
核心特性
- Instant HMR: Hot Module Replacement that doesn't degrade with app size
- File System Caching (Stable): Dev server artifacts cached on disk between restarts — up to 14x faster startup on large projects. Enabled by default in Next.js 16.1+, no config needed. Build caching planned next.
- Multi-environment builds: Browser, Server, Edge, SSR, React Server Components
- Native RSC support: Built for React Server Components from the ground up
- TypeScript, JSX, CSS, CSS Modules, WebAssembly: Out of the box
- Rust-powered: Incremental computation engine for maximum performance
- 极速HMR:热模块替换的性能不会随应用体积增大而下降
- 文件系统缓存(稳定版):开发服务器产物会在磁盘中缓存,重启项目时可复用——大型项目启动速度最高提升14倍。Next.js 16.1+版本默认启用,无需额外配置,后续还将支持构建缓存。
- 多环境构建:支持浏览器、服务端、Edge、SSR、React Server Components
- 原生RSC支持:从底层设计就面向React Server Components开发
- TypeScript、JSX、CSS、CSS Modules、WebAssembly:开箱即用支持
- Rust驱动:基于增量计算引擎实现极致性能
Configuration (Next.js 16)
配置方式(Next.js 16)
In Next.js 16, Turbopack config is top-level (moved from ):
experimental.turbopackjs
// next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
turbopack: {
// Resolve aliases (like webpack resolve.alias)
resolveAlias: {
'old-package': 'new-package',
},
// Custom file extensions to resolve
resolveExtensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
},
}
export default nextConfig在Next.js 16中,Turbopack的配置为顶层配置项(从迁移而来):
experimental.turbopackjs
// next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
turbopack: {
// 路径别名配置(类似webpack的resolve.alias)
resolveAlias: {
'old-package': 'new-package',
},
// 自定义可解析的文件后缀
resolveExtensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
},
}
export default nextConfigCSS and CSS Modules Handling
CSS与CSS Modules处理
Turbopack handles CSS natively without additional configuration.
Turbopack原生支持CSS处理,无需额外配置。
Global CSS
全局CSS
Import global CSS in your root layout:
tsx
// app/layout.tsx
import './globals.css'在根布局文件中导入全局CSS即可:
tsx
// app/layout.tsx
import './globals.css'CSS Modules
CSS Modules
CSS Modules work out of the box with files:
.module.csstsx
// components/Button.tsx
import styles from './Button.module.css'
export function Button({ children }) {
return <button className={styles.primary}>{children}</button>
}.module.csstsx
// components/Button.tsx
import styles from './Button.module.css'
export function Button({ children }) {
return <button className={styles.primary}>{children}</button>
}PostCSS
PostCSS
Turbopack reads your automatically. Tailwind CSS v4 works with zero config:
postcss.config.jsjs
// postcss.config.js
module.exports = {
plugins: {
'@tailwindcss/postcss': {},
autoprefixer: {},
},
}Turbopack会自动读取配置,Tailwind CSS v4可零配置使用:
postcss.config.jsjs
// postcss.config.js
module.exports = {
plugins: {
'@tailwindcss/postcss': {},
autoprefixer: {},
},
}Sass / SCSS
Sass / SCSS
Install and import files directly — Turbopack compiles them natively:
sass.scssbash
npm install sasstsx
import styles from './Component.module.scss'安装后可直接导入文件,Turbopack会原生完成编译:
sass.scssbash
npm install sasstsx
import styles from './Component.module.scss'Common CSS pitfalls
CSS常见问题
- CSS ordering differs from webpack: Turbopack may load CSS chunks in a different order. Avoid relying on source-order specificity across files — use more specific selectors or CSS Modules.
- in global CSS: Use standard CSS
@import— Turbopack resolves them, but circular imports cause build failures.@import - CSS-in-JS libraries: and
styled-componentswork but require their SWC plugins configured underemotionin next.config.compiler
- CSS加载顺序与webpack不同:Turbopack加载CSS chunk的顺序可能和webpack不同,不要依赖跨文件的源码顺序优先级,建议使用更明确的选择器或者CSS Modules。
- 全局CSS中的:使用标准CSS
@import语法即可,Turbopack会完成路径解析,但循环导入会导致构建失败。@import - CSS-in-JS库:和
styled-components可正常使用,但需要在next.config的emotion配置项中开启对应的SWC插件。compiler
Tree Shaking
Tree Shaking
Turbopack performs tree shaking at the module level in production builds. Key behaviors:
- ES module exports: Only used exports are included — write on each function/constant rather than barrel
exportexport * - Side-effect-free packages: Mark packages as side-effect-free in to enable aggressive tree shaking:
package.json
json
{
"name": "my-ui-lib",
"sideEffects": false
}- Barrel file optimization: Turbopack can skip unused re-exports from barrel files () when the package declares
index.ts"sideEffects": false - Dynamic imports: expressions create async chunk boundaries — Turbopack splits these into separate chunks automatically
import()
Turbopack在生产构建时会在模块层面执行Tree Shaking,核心特性如下:
- ES module导出:仅会打包被使用的导出内容,建议为每个函数/常量单独写,而非使用
export的 barrel 导出方式。export * - 无副作用包:在中标记包为无副作用,可开启更激进的Tree Shaking:
package.json
json
{
"name": "my-ui-lib",
"sideEffects": false
}- Barrel文件优化:当包声明了时,Turbopack会跳过barrel文件(
"sideEffects": false)中未被使用的重导出内容。index.ts - 动态导入:语法会自动创建异步chunk边界,Turbopack会自动将其拆分为独立的chunk。
import()
Diagnosing large bundles
大体积包诊断
Built-in analyzer (Next.js 16.1+, experimental): Works natively with Turbopack. Offers route-specific filtering, import tracing, and RSC boundary analysis:
ts
// next.config.ts
const nextConfig: NextConfig = {
experimental: {
bundleAnalyzer: true,
},
}Legacy : Still works as a fallback:
@next/bundle-analyzerbash
ANALYZE=true next buildts
// next.config.ts
import withBundleAnalyzer from '@next/bundle-analyzer'
const nextConfig = withBundleAnalyzer({
enabled: process.env.ANALYZE === 'true',
})({
// your config
})内置分析工具(Next.js 16.1+,实验性):原生支持Turbopack,提供路由维度过滤、导入链路追踪、RSC边界分析能力:
ts
// next.config.ts
const nextConfig: NextConfig = {
experimental: {
bundleAnalyzer: true,
},
}传统:仍可作为降级方案使用:
@next/bundle-analyzerbash
ANALYZE=true next buildts
// next.config.ts
import withBundleAnalyzer from '@next/bundle-analyzer'
const nextConfig = withBundleAnalyzer({
enabled: process.env.ANALYZE === 'true',
})({
// 你的配置
})Custom Loader Migration from Webpack
从Webpack自定义Loader迁移
Turbopack does not support webpack loaders directly. Here is how to migrate common patterns:
| Webpack Loader | Turbopack Equivalent |
|---|---|
| Built-in CSS support — remove loaders |
| Built-in — install |
| Built-in — reads |
| Built-in static asset handling |
| Use |
| Use |
| Use a build-time codegen step instead |
| Use native |
Turbopack不直接支持webpack loader,常见场景迁移方案如下:
| Webpack Loader | Turbopack等效方案 |
|---|---|
| 内置CSS支持,可直接移除对应loader |
| 内置支持,只需安装 |
| 内置支持,自动读取 |
| 内置静态资源处理能力 |
| 通过 |
| 使用 |
| 改用构建时代码生成步骤实现 |
| 使用原生 |
Configuring custom rules (loader replacement)
配置自定义规则(替代loader)
For loaders that have no built-in equivalent, use :
turbopack.rulesjs
// next.config.ts
const nextConfig: NextConfig = {
turbopack: {
rules: {
'*.svg': {
loaders: ['@svgr/webpack'],
as: '*.js',
},
},
},
}针对无内置等效方案的loader,可使用配置:
turbopack.rulesjs
// next.config.ts
const nextConfig: NextConfig = {
turbopack: {
rules: {
'*.svg': {
loaders: ['@svgr/webpack'],
as: '*.js',
},
},
},
}When migration isn't possible
无法迁移的场景
If a webpack loader has no Turbopack equivalent and no workaround, fall back to webpack:
js
const nextConfig: NextConfig = {
bundler: 'webpack',
}File an issue at github.com/vercel/next.js — the Turbopack team tracks loader parity requests.
如果某款webpack loader没有Turbopack等效方案,也没有替代实现,可降级使用webpack:
js
const nextConfig: NextConfig = {
bundler: 'webpack',
}你可以在github.com/vercel/next.js提交issue,Turbopack团队会追踪loader兼容性需求。
Production Build Diagnostics
生产构建诊断
Build failing with Turbopack
Turbopack构建失败
- Check for unsupported config: Remove any function from next.config — it's ignored by Turbopack and may mask the real config
webpack() - Verify : Ensure custom rules reference valid loaders that are installed
turbopack.rules - Check for Node.js built-in usage in edge/client: Turbopack enforces environment boundaries — ,
fs, etc. cannot be imported in client or edge bundlespath - Module not found errors: Ensure covers any custom resolution that was previously in webpack config
turbopack.resolveAlias
- 检查是否存在不支持的配置:移除next.config中的函数,Turbopack会忽略该配置,可能会掩盖真实配置问题
webpack() - 校验配置:确保自定义规则引用的loader已正确安装
turbopack.rules - 检查是否在edge/客户端代码中使用了Node.js内置模块:Turbopack会强制校验环境边界,、
fs等模块不能在客户端或edge构建包中导入path - 模块未找到错误:确保覆盖了之前webpack配置中的所有自定义路径解析规则
turbopack.resolveAlias
Build output too large
构建产物体积过大
- Audit directives — each client component boundary creates a new chunk
"use client" - Check for accidentally bundled server-only packages in client components
- Use package to enforce server/client boundaries at import time:
server-only
bash
npm install server-onlyts
// lib/db.ts
import 'server-only' // Build fails if imported in a client component- 检查指令的使用,每个客户端组件边界都会生成新的chunk
"use client" - 排查是否有服务端专用包被意外打包到客户端组件中
- 使用包在导入时强制校验服务端/客户端边界:
server-only
bash
npm install server-onlyts
// lib/db.ts
import 'server-only' // 如果在客户端组件中导入该文件,构建会直接失败Comparing webpack vs Turbopack output
对比webpack与Turbopack的构建产物
Run both bundlers and compare:
bash
undefined分别运行两个打包工具的构建命令后对比即可:
bash
undefinedTurbopack build (default in Next.js 16)
Turbopack构建(Next.js 16默认)
next build
next build
Webpack build
Webpack构建
BUNDLER=webpack next build
Compare `.next/` output sizes and page-level chunks.BUNDLER=webpack next build
对比`.next/`目录的输出体积和页面级chunk即可。Performance Profiling
性能分析
HMR profiling
HMR性能分析
Enable verbose HMR timing in development:
bash
NEXT_TURBOPACK_TRACING=1 next devThis writes a to the project root — open it in or Perfetto to see module-level timing.
trace.jsonchrome://tracing开发环境下开启HMR耗时详细日志:
bash
NEXT_TURBOPACK_TRACING=1 next devBuild profiling
构建性能分析
Profile production builds:
bash
NEXT_TURBOPACK_TRACING=1 next buildLook for:
- Long-running transforms: Indicates a slow SWC plugin or heavy PostCSS config
- Large module graphs: Reduce barrel file re-exports
- Cache misses: If incremental builds aren't hitting cache, check for files that change every build (e.g., generated timestamps)
分析生产构建的性能:
bash
NEXT_TURBOPACK_TRACING=1 next build重点关注:
- 耗时过长的转换任务:说明存在运行缓慢的SWC插件或者过于复杂的PostCSS配置
- 过大的模块依赖图:减少barrel文件的重导出
- 缓存未命中:如果增量构建没有命中缓存,排查是否有每次构建都会变更的文件(比如自动生成的时间戳)
Memory usage
内存占用
Turbopack's Rust core manages its own memory. If builds OOM:
- Increase Node.js heap:
NODE_OPTIONS='--max-old-space-size=8192' next build - Reduce concurrent tasks if running inside Turborepo:
turbo build --concurrency=2
Turbopack的Rust核心会自行管理内存,如果构建出现OOM:
- 增加Node.js堆内存:
NODE_OPTIONS='--max-old-space-size=8192' next build - 如果在Turborepo中运行,减少并发任务数:
turbo build --concurrency=2
Turbopack vs Webpack
Turbopack vs Webpack
| Feature | Turbopack | Webpack |
|---|---|---|
| Language | Rust | JavaScript |
| HMR speed | Constant (O(1)) | Degrades with app size |
| RSC support | Native | Plugin-based |
| Cold start | Fast | Slower |
| Ecosystem | Growing | Massive (loaders, plugins) |
| Status in Next.js 16 | Default | Still supported |
| Tree shaking | Module-level | Module-level |
| CSS handling | Built-in | Requires loaders |
| Production builds | Supported | Supported |
| 特性 | Turbopack | Webpack |
|---|---|---|
| 开发语言 | Rust | JavaScript |
| HMR速度 | 恒定(O(1)复杂度) | 随应用体积增大而下降 |
| RSC支持 | 原生支持 | 依赖插件实现 |
| 冷启动速度 | 快 | 较慢 |
| 生态 | 正在增长 | 非常成熟(loader、插件丰富) |
| 在Next.js 16中的状态 | 默认打包工具 | 仍可支持 |
| Tree Shaking | 模块级别 | 模块级别 |
| CSS处理 | 内置支持 | 需要额外loader |
| 生产构建 | 支持 | 支持 |
When You Might Need Webpack
适合使用Webpack的场景
- Custom webpack loaders with no Turbopack equivalent
- Complex webpack plugin configurations (e.g., )
ModuleFederationPlugin - Specific webpack features not yet in Turbopack (e.g., custom functions)
externals
To use webpack instead:
js
// next.config.ts
const nextConfig: NextConfig = {
bundler: 'webpack', // Opt out of Turbopack
}- 使用了无Turbopack等效方案的自定义webpack loader
- 存在复杂的webpack插件配置(比如)
ModuleFederationPlugin - 依赖Turbopack暂未支持的webpack特性(比如自定义函数)
externals
切换为webpack的配置如下:
js
// next.config.ts
const nextConfig: NextConfig = {
bundler: 'webpack', // 退出Turbopack默认配置
}Development vs Production
开发环境 vs 生产环境
- Development: Turbopack provides instant HMR and fast refresh
- Production: Turbopack handles the production build (replaces webpack in Next.js 16)
- 开发环境:Turbopack提供极速HMR和快速刷新能力
- 生产环境:Turbopack负责生产构建(在Next.js 16中替代webpack)
Common Issues
常见问题
- Missing loader equivalent: Some webpack loaders don't have Turbopack equivalents yet. Check Turbopack docs for supported transformations.
- Config migration: Move to top-level
experimental.turbopackin next.config.turbopack - Custom aliases: Use instead of
turbopack.resolveAlias.webpack.resolve.alias - CSS ordering changes: Test visual regressions when migrating — CSS chunk order may differ.
- Environment boundary errors: Server-only modules imported in client components fail at build time — use package.
server-only
- 缺少等效loader:部分webpack loader暂时没有对应的Turbopack实现,可查阅Turbopack官方文档确认支持的转换能力。
- 配置迁移:将next.config中的配置移动到顶层
experimental.turbopack配置项。turbopack - 自定义别名:使用替代
turbopack.resolveAlias。webpack.resolve.alias - CSS顺序变更:迁移时需要测试视觉回归问题,CSS chunk的加载顺序可能和webpack不同。
- 环境边界错误:在客户端组件中导入服务端专用模块会导致构建失败,可使用包提前校验。
server-only