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
- 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:热模块替换(Hot Module Replacement)功能,性能不会随应用规模增大而下降
- 多环境构建:支持浏览器、服务器、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的顺序可能不同。避免依赖跨文件的源码顺序优先级——使用更具体的选择器或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模块导出:仅包含被使用的导出——为每个函数/常量单独写,而非使用桶文件的
exportexport * - 无副作用包:在中标记包为无副作用,以启用更激进的Tree Shaking:
package.json
json
{
"name": "my-ui-lib",
"sideEffects": false
}- 桶文件优化:当包声明时,Turbopack可以跳过桶文件(
"sideEffects": false)中未使用的重导出index.ts - 动态导入:表达式会创建异步chunk边界——Turbopack会自动将这些拆分为独立的chunk
import()
Diagnosing large bundles
诊断大体积包
Use the Next.js bundle analyzer to inspect Turbopack's output:
bash
ANALYZE=true next buildOr install :
@next/bundle-analyzerjs
// next.config.ts
import withBundleAnalyzer from '@next/bundle-analyzer'
const nextConfig = withBundleAnalyzer({
enabled: process.env.ANALYZE === 'true',
})({
// your config
})使用Next.js包分析工具检查Turbopack的输出:
bash
ANALYZE=true next build或安装:
@next/bundle-analyzerjs
// 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 bundle中导入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配置
- 大型模块图:减少桶文件的重导出
- 缓存未命中:如果增量构建未命中缓存,检查是否有每次构建都会变化的文件(如生成时间戳的文件)
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的顺序可能不同。
- 环境边界错误:在客户端组件中导入仅服务器端模块会导致构建失败——使用包。
server-only