turbopack-bundler

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Turbopack Bundler

Turbopack Bundler

You are an expert in Turbopack, the incremental bundler optimized for JavaScript and TypeScript, written in Rust and built into Next.js. Follow these guidelines when working with Turbopack.
你是Turbopack领域的专家,Turbopack是专为JavaScript和TypeScript优化的增量打包工具,采用Rust编写,内置于Next.js中。使用Turbopack时请遵循以下指南。

Core Principles

核心原则

  • Turbopack is designed for incremental computation and caching
  • Function-level caching through the Turbo engine
  • Native Rust performance for fast builds
  • Built-in support for TypeScript and JSX
  • Optimized for Next.js integration
  • Abstracts away webpack configurations
  • Turbopack专为增量计算和缓存设计
  • 通过Turbo引擎实现函数级缓存
  • 原生Rust性能带来极速构建体验
  • 内置支持TypeScript和JSX
  • 针对Next.js集成做了优化
  • 抽象了webpack配置,无需手动编写

Project Structure

项目结构

project/
├── src/
│   ├── app/              # Next.js App Router
│   │   ├── layout.tsx
│   │   ├── page.tsx
│   │   └── globals.css
│   ├── components/       # Shared components
│   └── lib/              # Utility functions
├── public/               # Static assets
├── next.config.js        # Next.js configuration
├── tsconfig.json         # TypeScript config
└── package.json
project/
├── src/
│   ├── app/              # Next.js App Router
│   │   ├── layout.tsx
│   │   ├── page.tsx
│   │   └── globals.css
│   ├── components/       # 通用组件
│   └── lib/              # 工具函数
├── public/               # 静态资源
├── next.config.js        # Next.js 配置文件
├── tsconfig.json         # TypeScript 配置文件
└── package.json

Enabling Turbopack

启用Turbopack

Development Mode

开发模式

bash
undefined
bash
undefined

Next.js 13.4+

Next.js 13.4+ 版本

next dev --turbo
next dev --turbo

Or in package.json

或者在package.json中配置

{ "scripts": { "dev": "next dev --turbo" } }
undefined
{ "scripts": { "dev": "next dev --turbo" } }
undefined

Next.js Configuration

Next.js 配置

javascript
// next.config.js
module.exports = {
  experimental: {
    turbo: {
      // Turbopack-specific configuration
    }
  }
};
javascript
// next.config.js
module.exports = {
  experimental: {
    turbo: {
      // Turbopack专属配置
    }
  }
};

Configuration Options

配置选项

Custom Loaders

自定义加载器

javascript
// next.config.js
module.exports = {
  turbopack: {
    rules: {
      '*.svg': {
        loaders: ['@svgr/webpack'],
        as: '*.js'
      },
      '*.mdx': {
        loaders: ['@mdx-js/loader']
      }
    }
  }
};
javascript
// next.config.js
module.exports = {
  turbopack: {
    rules: {
      '*.svg': {
        loaders: ['@svgr/webpack'],
        as: '*.js'
      },
      '*.mdx': {
        loaders: ['@mdx-js/loader']
      }
    }
  }
};

Resolve Aliases

路径别名解析

javascript
// next.config.js
module.exports = {
  turbopack: {
    resolveAlias: {
      '@components': './src/components',
      '@lib': './src/lib',
      '@styles': './src/styles'
    }
  }
};
javascript
// next.config.js
module.exports = {
  turbopack: {
    resolveAlias: {
      '@components': './src/components',
      '@lib': './src/lib',
      '@styles': './src/styles'
    }
  }
};

Resolve Extensions

扩展名解析

javascript
// next.config.js
module.exports = {
  turbopack: {
    resolveExtensions: ['.tsx', '.ts', '.jsx', '.js', '.json']
  }
};
javascript
// next.config.js
module.exports = {
  turbopack: {
    resolveExtensions: ['.tsx', '.ts', '.jsx', '.js', '.json']
  }
};

Built-in Support

内置支持

Turbopack has built-in support for:
  • TypeScript: No configuration needed
  • JSX/TSX: Automatic transformation
  • CSS: Native CSS support
  • CSS Modules:
    .module.css
    files
  • PostCSS: Automatic processing
  • Static Assets: Images, fonts, etc.
No loaders needed for:
  • css-loader
  • postcss-loader
  • babel-loader
    (for
    @babel/preset-env
    )
Turbopack内置支持以下能力:
  • TypeScript: 无需额外配置即可使用
  • JSX/TSX: 自动完成转换
  • CSS: 原生CSS支持
  • CSS Modules: 支持
    .module.css
    文件
  • PostCSS: 自动处理
  • 静态资源: 图片、字体等资源
以下加载器无需额外安装配置:
  • css-loader
  • postcss-loader
  • babel-loader
    (针对
    @babel/preset-env
    场景)

TypeScript Configuration

TypeScript 配置

Recommended tsconfig.json

推荐的tsconfig.json配置

json
{
  "compilerOptions": {
    "target": "ES2017",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}
json
{
  "compilerOptions": {
    "target": "ES2017",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}

Path Aliases

路径别名

json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@components/*": ["src/components/*"],
      "@lib/*": ["src/lib/*"],
      "@styles/*": ["src/styles/*"]
    }
  }
}
json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@components/*": ["src/components/*"],
      "@lib/*": ["src/lib/*"],
      "@styles/*": ["src/styles/*"]
    }
  }
}

Code Organization

代码组织

Atomic Design Pattern

原子设计模式

src/
├── components/
│   ├── atoms/          # Basic building blocks
│   │   ├── Button/
│   │   └── Input/
│   ├── molecules/      # Combinations of atoms
│   │   ├── SearchBar/
│   │   └── NavItem/
│   ├── organisms/      # Complex components
│   │   ├── Header/
│   │   └── Footer/
│   └── templates/      # Page layouts
│       └── MainLayout/
├── app/
│   └── page.tsx
└── lib/
    └── utils.ts
src/
├── components/
│   ├── atoms/          # 基础构建块
│   │   ├── Button/
│   │   └── Input/
│   ├── molecules/      # 多个原子组合而成的组件
│   │   ├── SearchBar/
│   │   └── NavItem/
│   ├── organisms/      # 复杂组件
│   │   ├── Header/
│   │   └── Footer/
│   └── templates/      # 页面布局
│       └── MainLayout/
├── app/
│   └── page.tsx
└── lib/
    └── utils.ts

Component Structure

组件结构

Button/
├── Button.tsx
├── Button.module.css
├── Button.test.tsx
└── index.ts
Button/
├── Button.tsx
├── Button.module.css
├── Button.test.tsx
└── index.ts

Code Splitting

代码分割

Dynamic Imports

动态导入

typescript
import dynamic from 'next/dynamic';

const HeavyComponent = dynamic(() => import('@/components/HeavyComponent'), {
  loading: () => <p>Loading...</p>,
  ssr: false // Disable server-side rendering if needed
});
typescript
import dynamic from 'next/dynamic';

const HeavyComponent = dynamic(() => import('@/components/HeavyComponent'), {
  loading: () => <p>加载中...</p>,
  ssr: false // 按需禁用服务端渲染
});

Route-Based Splitting

基于路由的分割

Next.js automatically code-splits by route in the
app/
directory.
Next.js会自动对
app/
目录下的路由做代码分割。

Manual Splitting

手动分割

typescript
// Split large components
const ChartComponent = dynamic(() => import('./ChartComponent'));
const EditorComponent = dynamic(() => import('./EditorComponent'));
typescript
// 分割大型组件
const ChartComponent = dynamic(() => import('./ChartComponent'));
const EditorComponent = dynamic(() => import('./EditorComponent'));

Caching Strategy

缓存策略

Turbo Engine Caching

Turbo引擎缓存

  • Function-level caching for incremental builds
  • Only recomputes what changed
  • Persistent cache across builds
  • 增量构建采用函数级缓存
  • 仅重新计算发生变更的内容
  • 构建间持久化缓存

Optimizing for Cache

缓存优化

typescript
// Keep modules focused and small
// Changes to one module don't invalidate others

// Good: Separate concerns
export function formatDate(date: Date) { /* ... */ }
export function formatCurrency(amount: number) { /* ... */ }

// Avoid: Large utility files that change frequently
typescript
// 保持模块功能聚焦、体积小巧
// 单个模块的变更不会导致其他模块缓存失效

// 推荐:职责分离
export function formatDate(date: Date) { /* ... */ }
export function formatCurrency(amount: number) { /* ... */ }

// 不推荐:频繁变更的大型工具文件

Performance Best Practices

性能最佳实践

Module Organization

模块组织

  • Keep modules small and focused
  • Minimize cross-module dependencies
  • Use barrel exports sparingly
  • 保持模块小巧、功能聚焦
  • 最小化跨模块依赖
  • 谨慎使用桶导出

Import Optimization

导入优化

typescript
// Prefer specific imports
import { Button } from '@/components/Button';

// Avoid importing entire libraries
// Bad: import _ from 'lodash';
// Good: import debounce from 'lodash/debounce';
typescript
// 优先使用特定导入
import { Button } from '@/components/Button';

// 避免导入整个库
// 不推荐: import _ from 'lodash';
// 推荐: import debounce from 'lodash/debounce';

Static Analysis

静态分析

typescript
// Use const assertions for better tree-shaking
const ROUTES = {
  home: '/',
  about: '/about',
  contact: '/contact'
} as const;
typescript
// 使用const断言获得更好的tree-shaking效果
const ROUTES = {
  home: '/',
  about: '/about',
  contact: '/contact'
} as const;

CSS Handling

CSS处理

CSS Modules

CSS Modules

typescript
import styles from './Component.module.css';

function Component() {
  return <div className={styles.container}>Content</div>;
}
typescript
import styles from './Component.module.css';

function Component() {
  return <div className={styles.container}>内容</div>;
}

Global CSS

全局CSS

typescript
// app/layout.tsx
import './globals.css';
typescript
// app/layout.tsx
import './globals.css';

Tailwind CSS

Tailwind CSS

javascript
// tailwind.config.js
module.exports = {
  content: [
    './src/**/*.{js,ts,jsx,tsx,mdx}',
    './app/**/*.{js,ts,jsx,tsx,mdx}'
  ]
};
javascript
// tailwind.config.js
module.exports = {
  content: [
    './src/**/*.{js,ts,jsx,tsx,mdx}',
    './app/**/*.{js,ts,jsx,tsx,mdx}'
  ]
};

Environment Variables

环境变量

Next.js Environment Variables

Next.js环境变量

bash
undefined
bash
undefined

.env.local

.env.local

NEXT_PUBLIC_API_URL=https://api.example.com DATABASE_URL=postgresql://...

```typescript
// Client-side (must have NEXT_PUBLIC_ prefix)
const apiUrl = process.env.NEXT_PUBLIC_API_URL;

// Server-side only
const dbUrl = process.env.DATABASE_URL;
NEXT_PUBLIC_API_URL=https://api.example.com DATABASE_URL=postgresql://...

```typescript
// 客户端使用(必须带NEXT_PUBLIC_前缀)
const apiUrl = process.env.NEXT_PUBLIC_API_URL;

// 仅服务端使用
const dbUrl = process.env.DATABASE_URL;

Testing

测试

Test Organization

测试组织

src/
├── components/
│   └── Button/
│       ├── Button.tsx
│       └── Button.test.tsx    # Co-located test
└── __tests__/                 # Integration tests
    └── pages/
        └── home.test.tsx
src/
├── components/
│   └── Button/
│       ├── Button.tsx
│       └── Button.test.tsx    # 与源码同位置的测试文件
└── __tests__/                 # 集成测试
    └── pages/
        └── home.test.tsx

Testing Best Practices

测试最佳实践

  • Write unit tests for utility functions
  • Use React Testing Library for components
  • End-to-end tests with Cypress or Playwright
  • Keep tests close to the code they test
  • 为工具函数编写单元测试
  • 使用React Testing Library测试组件
  • 使用Cypress或Playwright编写端到端测试
  • 测试文件尽量靠近被测代码

Common Pitfalls

常见陷阱

Configuration Issues

配置问题

json
// Ensure correct tsconfig.json paths
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]  // Must match actual structure
    }
  }
}
json
// 确保tsconfig.json路径配置正确
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]  // 必须与实际目录结构匹配
    }
  }
}

Caching Problems

缓存问题

bash
undefined
bash
undefined

Clear Turbopack cache if issues arise

出现异常时可以清除Turbopack缓存

rm -rf .next
undefined
rm -rf .next
undefined

Compatibility

兼容性

  • Check dependency compatibility with Turbopack
  • Some webpack plugins may not work directly
  • Use Next.js configuration instead of webpack config
  • 检查依赖与Turbopack的兼容性
  • 部分webpack插件无法直接使用
  • 使用Next.js配置代替webpack配置

Migration from Webpack

从Webpack迁移

What Changes

变化点

  • No direct webpack.config.js
  • Use next.config.js for customization
  • Some loaders need Turbopack equivalents
  • 无需直接编写webpack.config.js
  • 使用next.config.js完成自定义配置
  • 部分加载器需要替换为Turbopack兼容版本

What Stays the Same

保持不变的内容

  • Import syntax
  • Dynamic imports
  • CSS Modules
  • TypeScript support
  • 导入语法
  • 动态导入
  • CSS Modules
  • TypeScript支持

Best Practices Summary

最佳实践总结

Do

推荐做法

  • Use Next.js configurations for customization
  • Leverage built-in TypeScript and JSX support
  • Organize code for incremental computation
  • Use dynamic imports for code splitting
  • Keep modules focused and small
  • 使用Next.js配置完成自定义
  • 充分利用内置的TypeScript和JSX支持
  • 按增量计算的要求组织代码
  • 使用动态导入做代码分割
  • 保持模块功能聚焦、体积小巧

Avoid

不推荐做法

  • Direct webpack configurations
  • Large barrel files that change frequently
  • Fighting against Next.js conventions
  • Ignoring TypeScript path configuration
  • 直接编写webpack配置
  • 频繁变更的大型桶文件
  • 违背Next.js约定的开发方式
  • 忽略TypeScript路径配置

Debugging

调试

Verbose Logging

详细日志输出

bash
NEXT_DEBUG_TURBOPACK=1 next dev --turbo
bash
NEXT_DEBUG_TURBOPACK=1 next dev --turbo

Build Analysis

构建分析

bash
undefined
bash
undefined

Check build output

查看构建输出

ANALYZE=true next build
undefined
ANALYZE=true next build
undefined

Common Issues

常见问题

  1. Slow initial build: Normal, subsequent builds are fast
  2. Module not found: Check path aliases in tsconfig.json
  3. CSS not loading: Ensure proper import syntax
  4. Type errors: Run
    tsc --noEmit
    separately
  1. 首次构建缓慢:属于正常现象,后续构建会非常快
  2. 模块未找到:检查tsconfig.json中的路径别名配置
  3. CSS未加载:确保导入语法正确
  4. 类型错误:单独运行
    tsc --noEmit
    检查