关于 nuxt-production
nuxt-production 是面向 Nuxt 4 项目的生产实践指南,涵盖水合、性能、测试、部署和 Nuxt 3 迁移。适合开发者查阅常见问题处理方法及代码模式。
主要功能
- 01水合问题排查与处理模式
- 02组件懒加载和缓存优化
- 03Vitest 与 Nuxt 测试示例
- 04部署配置和环境变量指引
- 05Nuxt 3 迁移步骤
适用场景
- 01排查服务端与客户端水合不匹配
- 02优化组件加载和路由缓存
- 03为组件或服务端路由编写测试
- 04将 Nuxt 3 项目迁移到 Nuxt 4
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ secondsky/ claude-skills --skill nuxt-production安装后在 Claude Code 中输入/nuxt-production确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/deployment-cloudflare.mdhydration.mdperformance.mdtesting-vitest.mdtemplates/wrangler.tomltemplates/tests/components/BlogPost.test.ts详细介绍
Nuxt 4 生产指南
水合、性能、测试、部署和迁移模式。
Nuxt 4 新功能
v4.2 功能(最新)
1. 数据获取中止控制
const controller = ref<AbortController>()
const { data } = await useAsyncData(
'users',
() => $fetch('/api/users', { signal: controller.value?.signal })
)
const abortRequest = () => {
controller.value?.abort()
controller.value = new AbortController()
}
2. 异步数据处理程序提取
- 客户端包体积缩小 39%
- 数据获取逻辑提取到服务端代码块
- 自动优化(无需配置)
3. 增强的错误处理
- 双重错误显示:自定义错误页面 + 技术叠加层
- 开发环境中的错误消息更清晰
v4.1 功能
1. 增强的代码块稳定性
- 导入映射可防止哈希变更级联
- 长期缓存效果更好
2. 延迟水合
<script setup>
const LazyComponent = defineLazyHydrationComponent(() =>
import('./HeavyComponent.vue')
)
</script>
与 v3 相比的破坏性变更
| 变更 | v3 | v4 |
|---|---|---|
| 源目录 | 根目录 | app/ |
| 数据响应性 | 深层 | 浅层(默认) |
| 默认值 | null | undefined |
| 路由中间件 | 客户端 | 服务端 |
| 应用清单 | 可选启用 | 默认启用 |
何时加载参考资料
在以下情况下加载 references/hydration.md:
- 调试“Hydration node mismatch”错误
- 实现 ClientOnly 组件
- 修复非确定性渲染问题
- 了解 SSR 与客户端渲染
在以下情况下加载 references/performance.md:
- 优化 Core Web Vitals 分数
- 实现延迟加载和代码拆分
- 配置缓存策略
- 减小包体积
在以下情况下加载 references/testing-vitest.md:
- 使用 @nuxt/test-utils 编写组件测试
- 在 Nuxt 上下文中测试组合式函数
- 模拟 Nuxt API(useFetch、useRoute)
- 设置 Vitest 配置
在以下情况下加载 references/deployment-cloudflare.md:
- 部署到 Cloudflare Pages 或 Workers
- 配置 wrangler.toml
- 设置 NuxtHub 集成
- 使用 D1、KV、R2 绑定
水合最佳实践
水合不匹配的成因
| 成因 | 示例 | 修复方法 |
|---|---|---|
| 非确定性值 | Math.random() | 使用 useState |
| 服务端使用浏览器 API | window.innerWidth | 使用 onMounted |
| 服务端日期/时间 | new Date() | 使用 useState 或 ClientOnly |
| 第三方脚本 | 分析工具 | 使用 ClientOnly |
修复模式
非确定性值:
<script setup>
const id = Math.random()
</script>
<script setup>
const id = useState('random-id', () => Math.random())
</script>
浏览器 API:
<script setup>
const width = window.innerWidth // Crashes on server!
</script>
<script setup>
const width = ref(0)
onMounted(() => {
width.value = window.innerWidth
})
</script>
ClientOnly 组件:
<template>
<ClientOnly>
<MyMapComponent />
<template #fallback>
<div class="skeleton">Loading map...</div>
</template>
</ClientOnly>
</template>
条件渲染:
<script setup>
const showWidget = ref(false)
onMounted(() => {
// Only show after hydration
showWidget.value = true
})
</script>
<template>
<AnalyticsWidget v-if="showWidget" />
</template>
性能优化
延迟加载组件
<script setup>
// Lazy load heavy components
const HeavyChart = defineAsyncComponent(() =>
import('~/components/HeavyChart.vue')
)
// With loading/error states
const HeavyChart = defineAsyncComponent({
loader: () => import('~/components/HeavyChart.vue'),
loadingComponent: LoadingSpinner,
errorComponent: ErrorFallback,
delay: 200,
timeout: 10000
})
</script>
<template>
<Suspense>
<HeavyChart :data="chartData" />
<template #fallback>
<LoadingSpinner />
</template>
</Suspense>
</template>
延迟水合
<script setup>
// Hydrate when visible in viewport
const LazyComponent = defineLazyHydrationComponent(
() => import('./HeavyComponent.vue'),
{ hydrate: 'visible' }
)
// Hydrate on user interaction
const InteractiveComponent = defineLazyHydrationComponent(
() => import('./InteractiveComponent.vue'),
{ hydrate: 'interaction' }
)
// Hydrate when browser is idle
const IdleComponent = defineLazyHydrationComponent(
() => import('./IdleComponent.vue'),
{ hydrate: 'idle' }
)
</script>
路由缓存
// nuxt.config.ts
export default defineNuxtConfig({
routeRules: {
// Static pages (prerendered at build)
'/': { prerender: true },
'/about': { prerender: true },
// SWR caching (1 hour)
'/blog/**': { swr: 3600 },
// ISR (regenerate every hour)
'/products/**': { isr: 3600 },
// SPA mode (no SSR)
'/dashboard/**': { ssr: false },
// Static with CDN caching
'/static/**': {
headers: { 'Cache-Control': 'public, max-age=31536000' }
}
}
})
图像优化
<template>
<NuxtImg
src="/images/hero.jpg"
alt="Hero image"
width="800"
height="400"
loading="lazy"
placeholder
format="webp"
/>
<NuxtPicture
src="/images/product.jpg"
alt="Product"
sizes="sm:100vw md:50vw lg:400px"
:modifiers="{ quality: 80 }"
/>
</template>
使用 Vitest 测试
设置
bun add -d @nuxt/test-utils vitest @vue/test-utils happy-dom
// vitest.config.ts
import { defineVitestConfig } from '@nuxt/test-utils/config'
export default defineVitestConfig({
test: {
environment: 'nuxt',
environmentOptions: {
nuxt: {
domEnvironment: 'happy-dom'
}
}
}
})
组件测试
// tests/components/UserCard.test.ts
import { describe, it, expect } from 'vitest'
import { mountSuspended } from '@nuxt/test-utils/runtime'
import UserCard from '~/components/UserCard.vue'
describe('UserCard', () => {
it('renders user name', async () => {
const wrapper = await mountSuspended(UserCard, {
props: {
user: { id: 1, name: 'John Doe', email: '[email protected]' }
}
})
expect(wrapper.text()).toContain('John Doe')
expect(wrapper.text()).toContain('[email protected]')
})
it('emits delete event', async () => {
const wrapper = await mountSuspended(UserCard, {
props: { user: { id: 1, name: 'John' } }
})
await wrapper.find('[data-test="delete-btn"]').trigger('click')
expect(wrapper.emitted('delete')).toHaveLength(1)
expect(wrapper.emitted('delete')[0]).toEqual([1])
})
})
模拟组合式函数
// tests/components/Dashboard.test.ts
import { describe, it, expect, vi } from 'vitest'
import { mountSuspended, mockNuxtImport } from '@nuxt/test-utils/runtime'
import Dashboard from '~/pages/dashboard.vue'
// Mock useFetch
mockNuxtImport('useFetch', () => {
return () => ({
data: ref({ users: [{ id: 1, name: 'John' }] }),
pending: ref(false),
error: ref(null)
})
})
describe('Dashboard', () => {
it('displays users from API', async () => {
const wrapper = await mountSuspended(Dashboard)
expect(wrapper.text()).toContain('John')
})
})
测试服务端路由
// tests/api/users.test.ts
import { describe, it, expect } from 'vitest'
import { $fetch, setup } from '@nuxt/test-utils/e2e'
describe('API: /api/users', async () => {
await setup({ server: true })
it('returns users list', async () => {
const users = await $fetch('/api/users')
expect(users).toHaveProperty('users')
expect(Array.isArray(users.users)).toBe(true)
})
it('creates a new user', async () => {
const result = await $fetch('/api/users', {
method: 'POST',
body: { name: 'Jane', email: '[email protected]' }
})
expect(result.user.name).toBe('Jane')
})
})
部署
Cloudflare Pages(推荐)
# Build and deploy
bun run build
bunx wrangler pages deploy .output/public
// nuxt.config.ts
export default defineNuxtConfig({
nitro: {
preset: 'cloudflare-pages'
}
})
Cloudflare Workers
// nuxt.config.ts
export default defineNuxtConfig({
nitro: {
preset: 'cloudflare-module'
}
})
# wrangler.toml
name = "my-nuxt-app"
compatibility_date = "2025-01-01"
compatibility_flags = ["nodejs_compat"]
[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "xxx-xxx-xxx"
[[kv_namespaces]]
binding = "KV"
id = "xxx-xxx-xxx"
Vercel
// nuxt.config.ts
export default defineNuxtConfig({
nitro: {
preset: 'vercel'
}
})
Netlify
// nuxt.config.ts
export default defineNuxtConfig({
nitro: {
preset: 'netlify'
}
})
NuxtHub(Cloudflare 一站式方案)
bun add @nuxthub/core
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@nuxthub/core'],
hub: {
database: true, // D1
kv: true, // KV
blob: true, // R2
cache: true // Cache API
}
})
// Usage in server routes
export default defineEventHandler(async (event) => {
const db = hubDatabase()
const kv = hubKV()
const blob = hubBlob()
// Use like regular Cloudflare bindings
const users = await db.prepare('SELECT * FROM users').all()
})
环境变量
# .env (development)
API_SECRET=dev-secret
DATABASE_URL=http://localhost:8787
# Production (Cloudflare)
wrangler secret put API_SECRET
wrangler secret put DATABASE_URL
# Production (Vercel/Netlify)
# Set in dashboard or CLI
从 Nuxt 3 迁移
步骤 1:更新 package.json
{
"devDependencies": {
"nuxt": "^4.0.0"
}
}
步骤 2:启用兼容模式
// nuxt.config.ts
export default defineNuxtConfig({
future: {
compatibilityVersion: 4
}
})
步骤 3:将文件移至 app/
# Create app directory
mkdir app
# Move files
mv components app/
mv composables app/
mv pages app/
mv layouts app/
mv middleware app/
mv plugins app/
mv assets app/
mv app.vue app/
mv error.vue app/
步骤 4:修复浅层响应性
// If mutating data.value properties:
const { data } = await useFetch('/api/user', {
deep: true // Enable deep reactivity
})
// Or replace entire value
data.value = { ...data.value, name: 'New Name' }
步骤 5:更新默认值
// v3: data.value is null
// v4: data.value is undefined
// Update null checks
if (data.value === null) // v3
if (!data.value) // v4 (works for both)
常见反模式
在服务端运行仅限客户端的代码
// WRONG
const width = window.innerWidth
// CORRECT
if (import.meta.client) {
const width = window.innerWidth
}
// Or use onMounted
onMounted(() => {
const width = window.innerWidth
})
非确定性 SSR
// WRONG - Different on server vs client
const id = Math.random()
const time = Date.now()
// CORRECT - Use useState for consistency
const id = useState('id', () => Math.random())
const time = useState('time', () => Date.now())
异步组件缺少 Suspense
<AsyncComponent />
<Suspense>
<AsyncComponent />
<template #fallback>
<LoadingSpinner />
</template>
</Suspense>
故障排除
水合不匹配:
- 检查是否使用了
window、document、localStorage - 用
ClientOnly包裹或使用onMounted - 查找
Math.random()、Date.now()、crypto.randomUUID()
构建错误:
rm -rf .nuxt .output node_modules/.vite && bun install
部署失败:
- 检查
nitro.preset是否与目标环境匹配 - 确认已设置环境变量
- 检查 wrangler.toml 绑定是否与代码匹配
测试失败:
- 确保已安装
@nuxt/test-utils - 检查 vitest.config.ts 是否包含
environment: 'nuxt' - 对异步组件使用
mountSuspended
相关技能
- nuxt-core:项目设置、路由、配置
- nuxt-data:组合式函数、数据获取、状态
- nuxt-server:服务端路由、API 模式
- cloudflare-d1:D1 数据库模式
版本:4.0.0 | 最后更新:2025-12-28 | 许可证:MIT
评论
支持 Markdown