VSCode / Cursor 效率配置

工具链的最后一公里是编辑器配置。一份好的 Snippets 库能让你 3 秒搭好组件骨架,一份好的 launch.json 能让你断点调试 Nitro API 而不是满屏 console.log,一份好的 tasks.json 能把 typecheck + lint + test 一键串起来。本章把 Nuxt4 开发中最值得配置的效率项整理成可直接复制的配置文件。

1. 推荐扩展

1.1 必装扩展

扩展作用
Vue - OfficialVue 3 / Nuxt 语法支持、类型检查
NuxtrNuxt 命令面板、文件生成器
Tailwind CSS IntelliSenseTailwind 类名补全和预览
ESLint代码规范检查
Error Lens行内显示错误/警告
Pretty TypeScript Errors美化 TypeScript 错误信息
GitLensGit blame、历史对比

1.2 settings.json 推荐配置

// .vscode/settings.json
{
  // Vue + TypeScript
  "editor.defaultFormatter": "dbaeumer.vscode-eslint",
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  },
 
  // TypeScript
  "typescript.tsdk": "node_modules/typescript/lib",
  "typescript.preferences.importModuleSpecifier": "non-relative",
 
  // Tailwind
  "tailwindCSS.experimental.classRegex": [
    ["ui:\\s*{([^}]*)}", "[\"'`]([^\"'`]*)[\"'`]"]
  ],
  "editor.quickSuggestions": {
    "strings": "on"
  },
 
  // 文件关联
  "files.associations": {
    "*.css": "tailwindcss"
  },
 
  // 排除不必要的文件
  "files.exclude": {
    ".nuxt": true,
    ".output": true,
    "node_modules": true
  },
 
  // Nuxt 自动导入不报错
  "vue.server.hybridMode": true
}

2. Nuxt4 代码片段库

2.1 Vue 组件模板

// .vscode/nuxt4.code-snippets
{
  "Nuxt Page": {
    "prefix": "npage",
    "scope": "vue",
    "body": [
      "<script setup lang=\"ts\">",
      "definePageMeta({",
      "  ${1:middleware: 'auth',}",
      "})",
      "",
      "const { data } = await useFetch('${2:/api/}')",
      "",
      "useSeoMeta({",
      "  title: '${3:Page Title}',",
      "})",
      "</script>",
      "",
      "<template>",
      "  <div>",
      "    $0",
      "  </div>",
      "</template>"
    ],
    "description": "Nuxt4 page with meta, data fetching, SEO"
  },
 
  "Nuxt Component": {
    "prefix": "ncomp",
    "scope": "vue",
    "body": [
      "<script setup lang=\"ts\">",
      "const props = defineProps<{",
      "  ${1:name}: ${2:string}",
      "}>()",
      "",
      "$0",
      "</script>",
      "",
      "<template>",
      "  <div>",
      "    {{ props.${1:name} }}",
      "  </div>",
      "</template>"
    ],
    "description": "Nuxt4 component with typed props"
  },
 
  "Nuxt Layout": {
    "prefix": "nlayout",
    "scope": "vue",
    "body": [
      "<script setup lang=\"ts\">",
      "$0",
      "</script>",
      "",
      "<template>",
      "  <div>",
      "    <AppHeader />",
      "    <main>",
      "      <slot />",
      "    </main>",
      "    <AppFooter />",
      "  </div>",
      "</template>"
    ],
    "description": "Nuxt4 layout"
  }
}

2.2 Server API 片段

{
  "API GET Handler": {
    "prefix": "napi-get",
    "scope": "typescript",
    "body": [
      "export default defineEventHandler(async (event) => {",
      "  ${1:const query = getValidatedQuery(event, schema.parse)}",
      "",
      "  $0",
      "",
      "  return { data: [] }",
      "})"
    ],
    "description": "Nuxt4 GET API route"
  },
 
  "API POST Handler": {
    "prefix": "napi-post",
    "scope": "typescript",
    "body": [
      "import { z } from 'zod'",
      "",
      "const schema = z.object({",
      "  ${1:field}: z.string(),",
      "})",
      "",
      "export default defineEventHandler(async (event) => {",
      "  const user = await requireAuth(event)",
      "  const body = await readValidatedBody(event, schema.parse)",
      "",
      "  $0",
      "})"
    ],
    "description": "Nuxt4 POST API route with auth + Zod"
  },
 
  "Cached API Handler": {
    "prefix": "napi-cached",
    "scope": "typescript",
    "body": [
      "export default defineCachedEventHandler(async (event) => {",
      "  $0",
      "  return { data: [] }",
      "}, {",
      "  maxAge: 60 * ${1:5},",
      "  swr: true,",
      "  name: '${2:cache-key}',",
      "})"
    ],
    "description": "Nuxt4 cached API route"
  }
}

2.3 Composable 片段

{
  "Nuxt Composable": {
    "prefix": "ncomposable",
    "scope": "typescript",
    "body": [
      "export function use${1:Name}() {",
      "  const ${2:data} = ref<${3:string}>(${4:''})${0}",
      "",
      "  return {",
      "    ${2:data},",
      "  }",
      "}"
    ],
    "description": "Nuxt4 composable"
  },
 
  "useFetch Composable": {
    "prefix": "nuse-fetch",
    "scope": "typescript,vue",
    "body": [
      "const { data: ${1:items}, status, error, refresh } = await useFetch('${2:/api/}', {",
      "  ${3:query: { page, limit \\},}",
      "  ${4:transform: (res) => res,}",
      "})"
    ],
    "description": "useFetch with common options"
  }
}

3. 断点调试配置

3.1 调试 Nitro Server

// .vscode/launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug Nuxt Server",
      "type": "node",
      "request": "launch",
      "program": "${workspaceFolder}/node_modules/.bin/nuxi",
      "args": ["dev"],
      "cwd": "${workspaceFolder}",
      "console": "integratedTerminal",
      "sourceMaps": true,
      "skipFiles": ["<node_internals>/**"],
      "env": {
        "NODE_OPTIONS": "--inspect"
      }
    },
    {
      "name": "Attach to Nuxt Server",
      "type": "node",
      "request": "attach",
      "port": 9229,
      "sourceMaps": true,
      "skipFiles": ["<node_internals>/**"],
      "restart": true
    }
  ]
}

使用方式

  1. 在 API 路由(如 server/api/videos.get.ts)中设置断点
  2. F5 启动 "Debug Nuxt Server"
  3. 浏览器访问对应 API 路由
  4. 断点命中,可以查看变量、调用栈、step through

3.2 调试 Vitest 测试

{
  "name": "Debug Vitest",
  "type": "node",
  "request": "launch",
  "program": "${workspaceFolder}/node_modules/.bin/vitest",
  "args": ["run", "--reporter=verbose", "${relativeFile}"],
  "cwd": "${workspaceFolder}",
  "console": "integratedTerminal",
  "sourceMaps": true
}

打开测试文件 → F5 → 只运行当前文件的测试,断点可以命中被测代码。

3.3 调试 Playwright E2E

{
  "name": "Debug Playwright",
  "type": "node",
  "request": "launch",
  "program": "${workspaceFolder}/node_modules/.bin/playwright",
  "args": ["test", "--headed", "--debug", "${relativeFile}"],
  "cwd": "${workspaceFolder}",
  "console": "integratedTerminal"
}

4. 任务自动化

4.1 tasks.json 配置

// .vscode/tasks.json
{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "dev",
      "type": "shell",
      "command": "pnpm dev",
      "isBackground": true,
      "problemMatcher": [],
      "group": "none"
    },
    {
      "label": "typecheck",
      "type": "shell",
      "command": "pnpm typecheck",
      "group": "test",
      "problemMatcher": ["$tsc"]
    },
    {
      "label": "lint",
      "type": "shell",
      "command": "pnpm lint",
      "group": "test",
      "problemMatcher": ["$eslint-stylish"]
    },
    {
      "label": "test",
      "type": "shell",
      "command": "pnpm test",
      "group": {
        "kind": "test",
        "isDefault": true
      },
      "problemMatcher": []
    },
    {
      "label": "build",
      "type": "shell",
      "command": "pnpm build",
      "group": {
        "kind": "build",
        "isDefault": true
      },
      "problemMatcher": []
    },
    {
      "label": "db:generate",
      "type": "shell",
      "command": "pnpm db:generate",
      "problemMatcher": []
    },
    {
      "label": "pre-commit check",
      "type": "shell",
      "command": "pnpm typecheck && pnpm lint && pnpm test",
      "group": "test",
      "problemMatcher": []
    }
  ]
}

使用Cmd+Shift+P → "Tasks: Run Task" → 选择任务。或者绑定快捷键。

4.2 常用快捷键绑定

// keybindings.json
[
  { "key": "cmd+shift+t", "command": "workbench.action.tasks.runTask", "args": "typecheck" },
  { "key": "cmd+shift+l", "command": "workbench.action.tasks.runTask", "args": "lint" },
  { "key": "cmd+shift+b", "command": "workbench.action.tasks.runTask", "args": "build" }
]

5. 工作区配置

5.1 Monorepo 多根目录

// nuxt4-project.code-workspace
{
  "folders": [
    { "name": "root", "path": "." },
    { "name": "web", "path": "apps/web" },
    { "name": "database", "path": "packages/database" },
    { "name": "shared", "path": "packages/shared" }
  ],
  "settings": {
    "typescript.tsdk": "node_modules/typescript/lib",
    "eslint.workingDirectories": [
      { "pattern": "apps/*" },
      { "pattern": "packages/*" }
    ]
  }
}

5.2 推荐的扩展列表文件

// .vscode/extensions.json
{
  "recommendations": [
    "vue.volar",
    "nuxtr.nuxtr-vscode",
    "bradlc.vscode-tailwindcss",
    "dbaeumer.vscode-eslint",
    "usernamehw.errorlens",
    "yoavbls.pretty-ts-errors",
    "eamodio.gitlens",
    "ms-playwright.playwright"
  ]
}

团队成员打开项目时,VSCode 会提示安装推荐扩展。

本章小结

  • 扩展:Vue Official + Nuxtr + Tailwind IntelliSense + ESLint + Error Lens 是 Nuxt4 开发必装组合
  • Snippets:npage/ncomp/napi-post 等代码片段 3 秒搭好骨架,保证团队代码风格一致
  • 调试:launch.json 支持断点调试 Nitro Server、Vitest 测试和 Playwright E2E
  • 任务:tasks.json 一键串联 typecheck + lint + test,绑定快捷键提升效率
  • 工作区:Monorepo 多根目录配置 + extensions.json 统一团队扩展