콘텐츠로 이동

Vue 3 + Nuxt 3 코딩 컨벤션

Raw

규칙은 두 가지로 나눠 적습니다.

  • 강제: ESLint·Prettier 설정에 들어 있는 규칙입니다. 커밋할 때 lefthook 이 스테이징한 파일에 실행해 자동으로 고치고, 고칠 수 없는 오류(error)가 남으면 커밋이 실패합니다. 경고(warn)는 표시만 됩니다. CI 에서는 검사하지 않습니다.
  • 권장: 팀이 지향하지만 도구로 검사하지 않는 규칙입니다. 리뷰에서 맞춥니다.
항목 워크스페이스 어노테이터
프레임워크 Nuxt 3.15 (Vue 3.5) Vue 3.5 + Vite 7
언어 TypeScript JavaScript 위주, 일부 TypeScript
컴포넌트 작성 <script setup lang="ts"> (거의 모든 컴포넌트) export default { ... } 객체. 그 안의 setup() 함수로 Composition API 를 쓰는 컴포넌트가 가장 많고, Options API(data·methods) 컴포넌트와 <script setup> 컴포넌트가 일부 섞여 있음
상태 관리 Pinia Setup 스토어, store/<도메인>/ Vuex 4 모듈, 어노테이터별 store/
서버 데이터 TanStack Query + DAO(useAPI()) axios 기반 서비스 모듈
컴포넌트 등록 Nuxt 자동 import (파일명이 곧 컴포넌트 이름) 명시적 import (옵션 객체는 components 에 등록)
컴포넌트 파일명 PascalCase (BadgeGroup.vue) — 권장 kebab-case (annotation-list.vue) — 권장. PascalCase 파일도 섞여 있음
SFC 블록 순서 template → script → style → i18n — 강제 검사 없음 (template → script → style 이 관례)
다국어 컴포넌트별 <i18n> 블록 + useI18n({ useScope: 'local' }), 공용 메시지 파일 vue-i18n, 공용 메시지 파일(ko.json·en.json)
ESLint ESLint 8, .eslintrc.json (@nuxtjs/eslint-config-typescript 기반) ESLint 9 flat config, eslint.config.mjs
import 정렬 import/order: 내장 → 외부 패키지 → ~/·상대 경로, 그룹 안 알파벳순 — 강제 perfectionist/sort-imports: 외부 → @/ → 상대 경로 그룹, 그룹 안 줄 길이순 — 강제 (@app/·@services/ 같은 별칭은 외부 묶음)
객체 키 정렬 검사 없음 perfectionist/sort-objects: 알파벳순 — 강제 (컴포넌트 옵션 객체 포함)
return 앞 빈 줄 검사 없음 padding-line-between-statements — 강제
패키지 매니저 npm pnpm
커밋 훅 lefthook (Prettier → ESLint --fix) lefthook (Prettier → ESLint --fix)

어노테이터에서 가장 흔한 형태입니다.

<template>
<div class="annotation-panel">{{ title }}</div>
</template>
<script>
import { computed } from 'vue'
import { useStore } from '@/app/app-store'
export default {
name: 'AnnotationPanel',
props: {
annotation: { required: true, type: Object }
},
setup(props) {
const { store } = useStore()
const sourceId = computed(() => store.state.annotator.currentSourceId)
const title = computed(() => props.annotation.label)
return { sourceId, title }
}
}
</script>
  • 옵션 객체의 키(name → props → setup)와 props 정의의 키(required → type)는 perfectionist/sort-objects 때문에 알파벳순입니다. Vue 스타일 가이드의 옵션 순서(name → components → props → data …)와 다르며, 커밋할 때 eslint --fix 가 알파벳순으로 다시 정렬합니다.
  • Vuex 스토어는 vuex 의 useStore 가 아니라 앱 스토어 모듈(@/app/app-store)의 useStore() 로 꺼냅니다. 반환값이 { store } 객체이므로 구조 분해합니다.
  • import 는 외부 패키지 → @/ 경로 → 상대 경로로 묶고(묶음 사이 빈 줄), 묶음 안에서는 줄이 짧은 것부터 둡니다. 묶음을 나누는 기준은 perfectionist 기본 internalPattern(^~/.+, ^@/.+)이라, @app/·@services/ 같은 별칭 경로는 @/ 묶음이 아니라 외부 패키지 묶음에 섞여 정렬됩니다.
  • return 앞에는 빈 줄을 둡니다.

Nuxt 3는 다수의 폴더를 자동 스캔하여 기능을 제공합니다. 폴더명은 kebab-case를 권장합니다.

워크스페이스의 주요 최상위 폴더입니다(scripts/·http/·docs/·build/ 같은 개발·배포용 폴더는 생략).

  • 디렉터리workspace
    • app.vue # 최상위 앱 컴포넌트
    • nuxt.config.ts # Nuxt 설정 파일
    • 디렉터리api/ # DAO(도메인별 API 클래스)와 요청·응답 타입
      • …
    • 디렉터리app/ # 라우터 옵션 (router.options.ts)
      • …
    • 디렉터리assets/ # CSS·폰트·SVG 아이콘(빌드 도구가 처리)
      • …
    • 디렉터리components/ # Vue 컴포넌트 (자동 임포트, 폴더 경로는 이름에 붙지 않음)
      • 디렉터리ui/ # 기본 UI 요소 (버튼, 입력 등)
        • …
      • 디렉터리shared/ # 여러 도메인이 함께 쓰는 복합 컴포넌트
        • …
      • 디렉터리project/ # 도메인별 컴포넌트
        • …
    • 디렉터리composables/ # 컴포저블 (도메인별 하위 폴더, 명시적 임포트)
      • …
    • 디렉터리config/ # i18n 공용 메시지 (ko.json, en.json)
      • …
    • 디렉터리constants/ # 상수
      • …
    • 디렉터리layouts/ # 페이지 레이아웃 (비동기 로드)
      • …
    • 디렉터리lib/ # 라이브러리 설정·확장 (FormKit 커스텀 입력·검증 규칙·테마, Tailwind 테마, cn() 헬퍼)
      • …
    • 디렉터리middleware/ # 라우트 미들웨어 (페이지 이동 전에 실행, 서버 미들웨어와 별개)
      • …
    • 디렉터리modules/ # 로컬 Nuxt 모듈
      • …
    • 디렉터리pages/ # 파일 기반 라우팅 페이지 컴포넌트
      • …
    • 디렉터리plugins/ # Nuxt 플러그인 (자동 등록)
      • …
    • 디렉터리public/ # 빌드 미처리 정적 파일 (favicon.ico, 이미지 등)
      • …
    • 디렉터리server/ # 서버 API(server/api/)·서버 유틸리티(server/utils/)·챗봇 자원(chatbot/, assets/)
      • …
    • 디렉터리store/ # Pinia 스토어 (도메인별 하위 폴더, 명시적 임포트)
      • …
    • 디렉터리stories/ # Storybook 스토리
      • …
    • 디렉터리tests/ # unit·integration(소스 경로 미러)·e2e 테스트. 소스 파일 옆에 둔 *.test.ts 도 있음
      • …
    • 디렉터리types/ # TypeScript 타입 정의
      • …
    • 디렉터리utils/ # 일반 유틸리티 (자동 임포트)
      • …

빌드 도구가 처리하는 정적 자산을 저장합니다.

  • 코드나 설정에서 직접 임포트
  • Vite에 의해 최적화됨

워크스페이스는 세 폴더를 씁니다.

  • assets/css/ — tailwind.css(Tailwind 모듈이 불러옴)와 pretendardvariable.css(nuxt.config.ts 의 css)
  • assets/fonts/ — Pretendard 글꼴 파일
  • assets/icons/ — SVG 아이콘. nuxt.config.ts 에서 Nuxt Icon 커스텀 컬렉션 datamaker 로 등록해 이름으로 씁니다
<template>
<Icon name="datamaker:play-circle" class="h-4 w-4" />
</template>

Vue 컴포넌트를 저장하며 자동으로 임포트됩니다.

네이밍 규칙:

  • Nuxt 기본값은 하위 폴더 경로가 이름 앞에 붙습니다(components/base/foo/Button.vue → <BaseFooButton />).
  • 워크스페이스는 nuxt.config.ts 에서 pathPrefix: false 로 설정해 파일명이 그대로 컴포넌트 이름이 됩니다. 그래서 파일명에 전체 이름을 씁니다.
  • 컴포넌트마다 kebab-case 폴더를 만들고 그 안에 PascalCase 파일과 타입 파일(types.d.ts)을 둡니다.
    • 예: components/shared/user-card/UserCard.vue → <UserCard />
  • 폴더가 달라도 파일명이 같으면 이름이 겹치므로 파일명을 다르게 짓습니다.

특수 기능:

  • 전역 컴포넌트: .global.vue 접미사 (과용 금지)
  • 지연 로딩: Lazy 접두사 사용 → <LazyFooBar />
  • 클라이언트 전용: .client.vue 접미사 (워크스페이스에서는 모달 등에 자주 씀)
  • 서버 전용: .server.vue 접미사
<!-- 지연 로딩 예제 -->
<template>
<div>
<!-- 필요할 때만 로드 -->
<LazyHeavyComponent v-if="showComponent" />
</div>
</template>

Composition API 기반 재사용 가능한 로직을 저장합니다.

규칙:

  • 파일명: useSomething.ts 형태 권장
  • Nuxt 는 composables/ 의 최상위 파일(과 하위 폴더의 index.ts)만 자동 임포트합니다. 더 깊은 파일까지 자동 임포트하려면 nuxt.config.ts 의 imports.dirs 를 설정해야 합니다.
  • 워크스페이스는 imports.dirs 를 설정하지 않고, 컴포저블을 도메인별 하위 폴더(composables/project/, composables/shared/ 등)에 두고 명시적으로 임포트합니다.
// 하위 폴더의 컴포저블은 경로를 적어 임포트
import { useAPI } from '~/composables/shared/useAPI'

페이지의 공통 레이아웃을 정의합니다.

중요사항:

  • 비동기 로드됨
  • 이름은 kebab-case로 변환
  • 단일 루트 요소 필수 (루트가 <slot />이면 안 됨)
layouts/default.vue
<template>
<div>
<Header />
<main>
<slot />
</main>
<Footer />
</div>
</template>

라우트 네비게이션 가드를 정의합니다.

세 가지 유형:

  1. 익명 미들웨어: 페이지 내부에서 직접 정의
  2. 명명 미들웨어: 파일명으로 참조
  3. 전역 미들웨어: .global.ts 접미사

전역 미들웨어는 파일명 알파벳순으로 실행되므로, 순서가 중요하면 01.auth.global.ts, 02.redirect.global.ts 처럼 번호 접두사를 붙입니다. 워크스페이스의 전역 미들웨어가 이 방식입니다.

middleware/auth.ts
import { useAuthTokens } from '~/composables/shared/useAuthTokens'
export default defineNuxtRouteMiddleware((to) => {
const { isAuthenticated } = useAuthTokens()
if (!isAuthenticated()) {
return navigateTo({ name: 'auth-login', query: { returnTo: to.fullPath } })
}
})
pages/dashboard.vue
<script setup>
definePageMeta({
middleware: 'auth'
})
</script>

파일 기반 라우팅 시스템을 사용합니다.

라우팅 패턴:

파일 라우트
pages/index.vue /
pages/about.vue /about
pages/posts/[id].vue /posts/:id (동적)
pages/posts/[[id]].vue /posts/:id? (선택적)
pages/[...slug].vue /* (캐치올)
pages/(marketing)/about.vue /about (그룹화)

단일 루트 요소 필수

Pinia를 사용한 상태 관리 스토어입니다.

  • Nuxt 의 Pinia 모듈은 기본적으로 stores/ 폴더를 자동 임포트하지만, 워크스페이스는 store/ 폴더를 쓰므로 스토어를 명시적으로 임포트합니다.
  • 스토어는 도메인별 하위 폴더에 <이름>Store.ts 로 두고, 내보내는 함수는 use<이름>Store, 스토어 id 는 kebab-case(예: 'project-creation')로 씁니다.

Setup 스토어 (권장)

현재 워크스페이스의 스토어는 모두 Setup 스토어입니다.

// store/shared/memberMeStore.ts (요약)
import { defineStore } from 'pinia'
import type { MemberRetrieveResData } from '~/api/worker/Member.types'
import { useAPI } from '~/composables/shared/useAPI'
export const useMemberMeStore = defineStore('member-me', () => {
const data = ref<MemberRetrieveResData | null>(null)
const isLoading = ref(false)
const fetchMemberMe = async (force = false) => {
if (data.value && !force) return data.value
isLoading.value = true
try {
data.value = await useAPI().worker.member.retrieveMe()
} finally {
isLoading.value = false
}
return data.value
}
const clearMemberMe = () => {
data.value = null
}
return { data, isLoading, fetchMemberMe, clearMemberMe }
})
// 사용하는 쪽: 경로를 적어 임포트
import { useMemberMeStore } from '~/store/shared/memberMeStore'
const memberMeStore = useMemberMeStore()

Options 스토어

Pinia 는 Options 스토어도 지원하지만 워크스페이스에서는 쓰지 않습니다.

// Options 스토어 예시 (워크스페이스에는 없는 형태)
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
getters: {
doubleCount: (state) => state.count * 2
},
actions: {
increment() {
this.count++
}
}
})

useState vs Pinia 선택 가이드

상황 권장 솔루션
단순 전역 상태 (테마, 로케일 등) useState
컴포넌트 간 공유되는 단일 값 useState
복잡한 상태 + 여러 액션 Pinia
상태 지속성 (localStorage 등) Pinia
DevTools 디버깅 필요 Pinia
// ✅ 간단한 상태: useState 사용
export const useTheme = () => useState<'light' | 'dark'>('theme', () => 'light')
export const useLocale = () => useState<string>('locale', () => 'ko-KR')
// ✅ 복잡한 상태: Pinia 사용
export const useCartStore = defineStore('cart', () => {
const items = ref<CartItem[]>([])
const total = computed(() => items.value.reduce((sum, item) => sum + item.price, 0))
function addItem(item: CartItem) { /* ... */ }
function removeItem(id: string) { /* ... */ }
function checkout() { /* ... */ }
return { items, total, addItem, removeItem, checkout }
})

새로 다루는 서버 데이터는 스토어에 복사하지 않고 TanStack Query 캐시로 다루는 것을 권장합니다(4.3 데이터 패칭). 다만 현재 사용자·알림처럼 미들웨어·플러그인과 여러 화면이 함께 쓰는 데이터는 위 memberMeStore 와 myInfoStore·notificationStore 처럼 스토어에 담아 둔 경우가 있습니다.

서버 사이드 API와 로직을 정의합니다.

구조:

  • server/api/ → /api/* 엔드포인트
  • server/routes/ → /api 없는 라우트
  • server/middleware/ → 서버 미들웨어
  • server/utils/ → 서버 유틸리티

워크스페이스는 이 중 server/api/(챗봇 스트리밍·인증 엔드포인트와 host·uuid 등)와 server/utils/ 만 씁니다. 그 밖에 챗봇 문서 검색용 자원을 server/chatbot/·server/assets/chatbot/ 에 둡니다.

server/api/users.ts
export default defineEventHandler(async (event) => {
const users = await fetchUsers()
return users
})
// server/api/users/[id].get.ts
export default defineEventHandler(async (event) => {
const id = getRouterParam(event, 'id')
const user = await fetchUser(id)
return user
})

일반 유틸리티 함수를 저장하며 자동 임포트됩니다.

utils/format.ts
export const formatDate = (date: Date) => {
return date.toLocaleDateString('ko-KR')
}
// 자동 임포트되어 어디서든 사용 가능
// const formatted = formatDate(new Date())

빌드 처리 없이 그대로 제공되는 정적 파일입니다.

  • public/favicon.ico → /favicon.ico
  • public/image_placeholder.svg → /image_placeholder.svg

  • 워크스페이스는 PascalCase 파일명(BadgeGroup.vue)을 쓰고 템플릿에서도 PascalCase(<BadgeGroup>)로 씁니다. 어노테이터는 kebab-case 파일명을 권장합니다(저장소별 차이). 파일명은 ESLint 가 검사하지 않습니다.
  • 베이스 컴포넌트: Vue 스타일 가이드는 Base, App, V 접두사를 권장합니다(예: BaseButton.vue, BaseTable.vue).
    • HTML 요소/다른 베이스 컴포넌트/외부 UI만 포함, 글로벌 상태 금지.
    • 워크스페이스의 기본 UI 컴포넌트(components/ui/)는 접두사 없이 씁니다(Button, Dialog). Base 접두사는 BaseHeader.vue, BaseWorkerPullModal.vue 처럼 다른 컴포넌트가 감싸서 쓰는 공용 부모 컴포넌트에 붙어 있습니다. 스타일 가이드의 베이스 컴포넌트와 뜻이 달라 API 호출이나 라우트 접근을 하기도 합니다.
  • 부모-자식 관계가 강한 경우, 부모 이름을 접두사로(예: TodoListItemButton.vue).
  • 일반 규칙: 상위 개념 → 하위 개념 순(예: SearchButtonClear.vue).
  • HTML 요소와 헷갈리지 않도록 두 단어 이상으로 짓는 것을 권장합니다. 다만 두 저장소 모두 vue/multi-word-component-names 를 꺼 두었고, 워크스페이스의 기본 UI 컴포넌트(components/ui/)는 Button, Dialog 처럼 한 단어 이름을 씁니다.
  • pages/index.vue → / 루트. 하위 폴더의 index.vue는 해당 디렉터리의 기본 경로.
  • 동적 라우트: [id].vue / 선택적 파라미터: [[param]].vue
  • 혼합 세그먼트: users-[group]/[id].vue
  • 캐치올: [...slug].vue
  • 라우트 그룹: pages/(group)/... (URL 영향 없음)
  • 페이지는 단일 루트 요소 필수.
  • 레이아웃 이름은 kebab-case로 변환. 파일명과 일치.
    • 예: layouts/custom.vue → custom 레이아웃
  • 중첩 폴더는 경로 기반 이름 부여
    • 예: ~/layouts/desktop/default.vue → desktop-default
  • 단일 루트 요소 필요(루트 <slot /> 금지).

2.4 컴포저블·유틸리티·스토어 파일 명

섹션 제목: “2.4 컴포저블·유틸리티·스토어 파일 명”
  • 컴포저블: composables/<도메인>/useSomething.ts(함수명 useSomething). 노출 함수는 camelCase.
  • 유틸리티: 함수 이름은 camelCase. 기본 내보내기(default export)는 파일명을 camelCase 로 바꾼 이름으로 자동 임포트됩니다(utils/random-entry.ts → randomEntry()).
  • Pinia 스토어: store/<도메인>/<이름>Store.ts + defineStore('<kebab-case id>', ...) → 내보내기 함수 use<이름>Store (예: store/shared/memberMeStore.ts, defineStore('member-me', ...), useMemberMeStore).
    • 각 파일 1 스토어 권장.

2.5 서버 API·미들웨어·플러그인 파일 명

섹션 제목: “2.5 서버 API·미들웨어·플러그인 파일 명”
  • API: server/api/hello.ts → /api/hello
    • 동적: [name].ts, 메서드별: .get.ts, .post.ts, …
  • server routes: /api 접두사 제거 필요 시 server/routes/*
  • server middleware: server/middleware/log.ts (모든 요청 전 실행)
  • server plugins: server/plugins/myPlugin.ts (Nitro 플러그인)
  • 라우트 미들웨어: middleware/*.ts (kebab-case, 전역은 .global, 실행 순서가 필요하면 번호 접두사)

3. 함수·변수·컴포저블 네이밍 규칙

섹션 제목: “3. 함수·변수·컴포저블 네이밍 규칙”
  • camelCase 사용(JS/TS 함수·변수·반응형 상태 포함).
  • 불린 변수: is*, has*, should* 접두사(예: isAuthenticated, hasPermission).
  • 이벤트 핸들러: handle*, on*(예: handleSubmit, onClick).
  • 비동기/데이터 패칭: fetch*, load*, get*(예: fetchUserProfile, loadPosts).
  • 컴포저블: use*(예: useAuth, useProjectQuery).
  • Pinia 스토어: use*Store(예: useMemberMeStore).
  • 워크스페이스는 <script setup lang="ts"> 를 씁니다(간결/타입 추론 우수). 어노테이터는 저장소별 차이를 참고하세요.
  • SFC 블록 순서: <template> → <script> → <style> → <i18n>, 블록 사이에는 빈 줄 — 강제(vue/block-order, vue/padding-line-between-blocks).
  • 각 파일 하나의 컴포넌트 — 강제(경고, vue/one-component-per-file).
  • this 가 필요 없으면 화살표 함수를 씁니다(권장). 세미콜론은 Prettier 가 지웁니다.
  • 속성 이름과 값 변수 이름이 같으면 Vue 3.4+ 축약형을 씁니다(권장): :value="value" → :value.
  • class, style, id, 네이티브 이벤트는 props 로 받지 않고 fallthrough 속성으로 넘깁니다(권장).

예제: 기본 컴포넌트 구조

<template>
<div>
<h2>{{ title }}</h2>
<p>Count: {{ localCount }}</p>
<p>Double: {{ doubleCount }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script setup lang="ts">
// Nuxt 3에서는 ref, computed, onMounted 등이 auto-import됨
// import { ref, computed, onMounted } from 'vue' ← 불필요
// Props 정의
const props = defineProps<{
title: string
count?: number
}>()
// Emits 정의 (Vue 3.3+ named tuple 문법 - 권장)
const emit = defineEmits<{
update: [value: number]
delete: []
}>()
// 또는 기존 call signature 문법 (Vue 3.3 이전 호환)
// const emit = defineEmits<{
// (e: 'update', value: number): void
// (e: 'delete'): void
// }>()
// 반응형 상태
const localCount = ref(props.count ?? 0)
// Computed
const doubleCount = computed(() => localCount.value * 2)
// 메서드
const increment = () => {
localCount.value++
emit('update', localCount.value)
}
// 라이프사이클
onMounted(() => {
// 초기화 로직
})
</script>
<style scoped>
button {
padding: 0.5rem 1rem;
background-color: #42b883;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>

defineModel을 활용한 양방향 바인딩 (Vue 3.4+)

섹션 제목: “defineModel을 활용한 양방향 바인딩 (Vue 3.4+)”

Vue 3.4부터 도입된 defineModel() 매크로는 v-model 양방향 바인딩을 간편하게 구현합니다.

기본 사용법

<template>
<input v-model="model" />
</template>
<script setup lang="ts">
// 선언 방식별 예시입니다. 실제로는 하나만 씁니다.
// 기본 v-model 바인딩 (modelValue prop)
const model = defineModel()
// 타입 지정
const model = defineModel<string>()
// 필수 + 타입 지정
const model = defineModel<string>({ required: true })
// 기본값 지정
const model = defineModel({ default: 0 })
</script>

Named Model (v-model:name)

<template>
<input v-model="firstName" placeholder="이름" />
<input v-model="lastName" placeholder="성" />
</template>
<script setup lang="ts">
// v-model:title 바인딩
const title = defineModel('title')
// 여러 v-model 지원
const firstName = defineModel('firstName')
const lastName = defineModel('lastName')
</script>

부모 컴포넌트에서 사용

<template>
<!-- 기본 v-model -->
<MyInput v-model="searchText" />
<!-- Named v-model -->
<UserNameForm
v-model:first-name="user.firstName"
v-model:last-name="user.lastName"
/>
</template>

Modifiers 접근

<script setup lang="ts">
// modifiers 객체 접근
const [model, modifiers] = defineModel<string, 'trim' | 'uppercase'>()
// modifiers 예: { trim: true, uppercase: true }
console.log(modifiers)
</script>

참고: defineModel()은 이전의 defineProps + defineEmits 조합을 대체하여 더 간결한 양방향 바인딩을 제공합니다.

컴포저블은 Vue의 Composition API를 활용하여 재사용 가능한 상태 로직을 캡슐화합니다.

예제: 기본 컴포저블

composables/shared/useCounter.ts
export const useCounter = (initialValue = 0) => {
const count = ref(initialValue)
const doubleCount = computed(() => count.value * 2)
const increment = () => {
count.value++
}
const decrement = () => {
count.value--
}
const reset = () => {
count.value = initialValue
}
return {
count: readonly(count),
doubleCount,
increment,
decrement,
reset
}
}

예제: 서버 데이터 조회 컴포저블

서버 데이터는 직접 ref 와 loading 상태를 만들지 않고 TanStack Query 로 감쌉니다. Nuxt 내장 useFetch 와 이름이 겹치는 컴포저블은 만들지 않습니다.

// composables/project/useProjectQuery.ts (예시)
import { useQuery } from '@tanstack/vue-query'
import type { Ref } from 'vue'
import { useAPI } from '~/composables/shared/useAPI'
export const useProjectQuery = (projectId: Ref<number>) => {
const api = useAPI()
return useQuery({
// [DAO 클래스 이름, 메서드 이름, 조건] — ref 가 들어 있으면 값이 바뀔 때 다시 조회한다
queryKey: [api.project.project.constructor.name, api.project.project.retrieve.name, { path: projectId }],
queryFn: () => api.project.project.retrieve({ path: projectId.value })
})
}

유틸리티는 순수 함수로 작성하며, Vue의 반응성 시스템과 독립적입니다.

예제: 유틸리티 함수

utils/format.ts
export const formatCurrency = (value: number, locale = 'ko-KR', currency = 'KRW') => {
return new Intl.NumberFormat(locale, {
style: 'currency',
currency
}).format(value)
}
export const formatDate = (date: Date | string, format = 'yyyy-MM-dd') => {
const d = typeof date === 'string' ? new Date(date) : date
// 포맷팅 로직
return d.toISOString().split('T')[0]
}
  • 컴포저블: ref, reactive, computed 등으로 상태 구성 후 필요한 값 반환
  • 파일명 = 함수명 일치 권장 (예: useAuth.ts → useAuth())
  • 유틸리티: 순수 함수 지향, 부수 효과 회피
  • 스토어 정의(defineStore)는 store/ 에, 재사용 로직은 composables/ 에 둡니다
  • ref·computed·useRoute 같은 Vue·Nuxt API 는 auto-import 를 쓰고, 하위 폴더의 컴포저블·스토어는 경로를 적어 임포트합니다
  • 새 유틸리티를 만들기 전에 lodash-es 나 VueUse 에 이미 있는지 확인합니다

PascalCase를 사용하며, I 접두사는 지양합니다. 타입만 담은 파일은 .d.ts 확장자를 씁니다(예: 컴포넌트 폴더의 types.d.ts).

// ❌ 나쁜 예
interface IUserProfile {
name: string
email: string
}
// ✅ 좋은 예
interface UserProfile {
name: string
email: string
}
type ApiResponse<T> = {
data: T
status: number
message?: string
}

상수 이름은 SCREAMING_SNAKE_CASE 로 씁니다. enum 대신 상수 객체를 사용하여 타입 안전성과 유연성을 확보합니다.

// ❌ enum 사용 지양
enum UserRole {
ADMIN = 'admin',
USER = 'user',
GUEST = 'guest'
}
// ✅ 상수 객체 사용 권장
export const USER_ROLE = {
ADMIN: 'admin',
USER: 'user',
GUEST: 'guest'
} as const
export type UserRole = typeof USER_ROLE[keyof typeof USER_ROLE]

포맷(줄바꿈·들여쓰기·따옴표·세미콜론)은 Prettier, 그 밖의 규칙은 ESLint 가 맡습니다. 두 저장소 모두 eslint-config-prettier 로 Prettier 와 겹치는 ESLint 규칙을 끄고, 커밋할 때 lefthook 이 스테이징한 파일에 두 도구를 실행합니다. Prettier 설정과 커밋 훅은 Prettier 문서를 참고하세요.

.eslintrc.json 전체입니다. @nuxtjs/eslint-config-typescript 는 standard, plugin:vue/vue3-recommended, @typescript-eslint/recommended 규칙 묶음을 포함합니다.

{
"root": true,
"extends": ["@nuxtjs/eslint-config-typescript", "plugin:storybook/recommended", "prettier"],
"parserOptions": {
"sourceType": "module"
},
"rules": {
"vue/multi-word-component-names": "off",
"vue/block-order": [
"error",
{
"order": ["docs", "template", "script", "style", "i18n:not([locale=en])", "i18n[locale=en]"]
}
],
"vue/padding-line-between-blocks": ["error"],
"import/order": [
"error",
{
"groups": ["builtin", "external", "internal"],
"alphabetize": {
"order": "asc"
}
}
]
}
}

자주 걸리는 규칙입니다.

규칙 수준 내용
vue/block-order 오류 SFC 블록 순서 template → script → style → i18n
vue/padding-line-between-blocks 오류 SFC 블록 사이 빈 줄
import/order 오류 node: 내장 → 외부 패키지 → ~/·상대 경로 순, 그룹 안에서는 알파벳순
@typescript-eslint/no-unused-vars 오류 쓰지 않는 변수·인자(_ 로 시작하는 인자는 제외)
vue/no-unused-components 오류 등록하고 쓰지 않는 컴포넌트
vue/no-reserved-component-names 오류 name 옵션이 HTML 요소·Vue 내장 컴포넌트 이름과 같음
prefer-const, no-var 오류 재할당하지 않으면 const, var 금지
vue/attribute-hyphenation, vue/v-on-event-hyphenation 경고 템플릿에서 props·이벤트 이름은 kebab-case
vue/require-explicit-emits 경고 발생시키는 이벤트는 defineEmits 에 선언
vue/require-default-prop 경고 필수가 아닌 prop 의 기본값
vue/no-v-html 경고 v-html 사용
no-console 경고 console 사용
vue/multi-word-component-names 끔 한 단어 컴포넌트 이름 허용
@typescript-eslint/no-explicit-any 끔 any 허용

npm 스크립트에 lint 명령은 없습니다. 직접 검사하려면 npx eslint <파일 또는 폴더> 를 실행합니다.

ESLint 9 flat config(eslint.config.mjs)입니다. eslint-plugin-vue 는 flat/base 만 켜므로 vue3-recommended 규칙 묶음(vue/no-v-html, vue/attribute-hyphenation 등)은 검사하지 않습니다.

규칙 수준 내용
perfectionist/sort-* (20개) 오류 정렬 규칙. import·export·enum·클래스 멤버·union 타입·switch case 는 줄 길이순, 객체 키·named import·인터페이스·객체 타입·변수 선언 등은 알파벳순
padding-line-between-statements 오류 return 앞에 빈 줄
no-dupe-class-members 오류 클래스 멤버 이름 중복
@typescript-eslint/no-unused-vars 경고 쓰지 않는 변수(_ 로 시작하는 변수·인자·catch 변수는 제외)
@typescript-eslint/no-explicit-any 경고 any 사용
vue/no-unused-components 경고 등록하고 쓰지 않는 컴포넌트
vue/multi-word-component-names, vue/no-v-html 끔
  • 설정 파일에는 vue/multiline-html-element-content-newline: 'error' 도 있지만, 마지막에 둔 eslint-config-prettier 가 끄므로 실제로는 검사하지 않습니다.
  • 검사: pnpm lint(src 전체), 타입 검사: pnpm type-check.

구조 분해 시 반응성을 잃지 않도록 storeToRefs()를 사용합니다.

import { useMemberMeStore } from '~/store/shared/memberMeStore'
// ❌ 나쁜 예 - 반응성 손실
const memberMeStore = useMemberMeStore()
const { data, isLoading } = memberMeStore // 반응성 손실!
// ✅ 좋은 예 - 반응성 유지
const memberMeStore = useMemberMeStore()
const { data, isLoading } = storeToRefs(memberMeStore)
// 메서드는 직접 구조 분해 가능
const { fetchMemberMe, clearMemberMe } = memberMeStore
// ❌ 나쁜 예
const state = reactive({ count: 0, name: 'John' })
const { count, name } = state // 반응성 손실
// ✅ 좋은 예 1: toRefs 사용
const state = reactive({ count: 0, name: 'John' })
const { count, name } = toRefs(state)
// ✅ 좋은 예 2: 객체 그대로 사용
const state = reactive({ count: 0, name: 'John' })
// 템플릿에서: {{ state.count }}

워크스페이스는 Nuxt 내장 useFetch·useAsyncData 를 쓰지 않고, TanStack Query(@tanstack/vue-query v5)와 DAO 로 서버 데이터를 다룹니다.

용도 사용하는 것
API 호출 useAPI() 가 돌려주는 DAO. 도메인별 API 클래스가 묶여 있고(api.project.project.retrieve(...)), 요청·응답 타입은 OpenAPI 스펙에서 생성
조회 useQuery
서버 렌더링 중에 미리 조회 워크스페이스 컴포저블 usePrefetchQuery 를 await 하는 방식이 가장 많음(내부에서 useQuery 를 만들고 suspense() 결과를 바로 돌려주며, onServerPrefetch 에도 등록). 돌려받는 값은 그 시점의 결과라 반응형이 아니므로, 무효화·재조회 뒤에도 화면에 반영할 값은 useQuery 결과를 바인딩하고 onServerPrefetch 에서 suspense() 를 기다림
생성·수정·삭제 useMutation. 성공하면 useQueryClient() 로 관련 쿼리를 다시 가져오거나(refetchQueries, 가장 많이 씀) 무효화(invalidateQueries)하거나 캐시를 직접 갱신(setQueryData)

서버 렌더링 중에 채운 쿼리 캐시는 플러그인이 dehydrate/hydrate 로 클라이언트에 넘깁니다. 쿼리 기본 옵션은 staleTime: 0, gcTime: 0, 재시도 없음(retry: 0), 창 포커스 시 재조회 안 함(refetchOnWindowFocus: false)입니다.

<template>
<section>
<h1>{{ project?.title }}</h1>
<button type="button" :disabled="isPending" @click="rename('새 이름')">이름 변경</button>
</section>
</template>
<script setup lang="ts">
import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query'
import { useAPI } from '~/composables/shared/useAPI'
const api = useAPI()
const route = useRoute()
const queryClient = useQueryClient()
const projectId = Number(route.params.project_id)
// 화면에 계속 반영할 데이터는 useQuery 결과를 바인딩한다
const projectQuery = useQuery({
queryKey: [api.project.project.constructor.name, api.project.project.retrieve.name, { path: projectId }],
queryFn: () => api.project.project.retrieve({ path: projectId })
})
const project = computed(() => projectQuery.data.value)
// 서버 렌더링 중에 미리 가져온다
onServerPrefetch(async () => {
await projectQuery.suspense()
})
// 변경 요청: 성공하면 [클래스 이름, 메서드 이름] 으로 시작하는 쿼리를 모두 무효화해 다시 가져온다
const { mutate: rename, isPending } = useMutation({
mutationFn: (title: string) => api.project.project.partialUpdate({ path: projectId, body: { title } }),
onSuccess: () =>
queryClient.invalidateQueries({
queryKey: [api.project.project.constructor.name, api.project.project.retrieve.name]
})
})
</script>
  • usePrefetchQuery 는 await 한 시점의 결과(반응형이 아닌 값)를 돌려줍니다. 이 값을 템플릿에 바인딩하면 무효화·재조회 뒤에도 화면이 바뀌지 않으므로, 계속 반영할 값은 위처럼 useQuery 결과를 씁니다.
  • queryKey 는 워크스페이스에서 흔히 쓰는 [DAO 클래스 이름, 메서드 이름, 조건] 형태를 따릅니다. 다른 형태로 만들면 이 앞부분으로 다시 가져오거나 무효화하는 다른 화면의 refetchQueries·invalidateQueries 에 걸리지 않습니다.
  • 조회 조건(검색어, 페이지, id)은 queryKey 에 넣습니다. 결과가 키별로 캐시되므로 조건이 빠르게 바뀌어도 이전 조건의 늦은 응답이 현재 화면을 덮지 않습니다. 직접 비동기 로직을 짤 때의 경합 방지는 비동기 경합 방지 패턴을 참고하세요.
  • 여러 조회는 useQuery 를 여러 번 호출하면 병렬로 실행됩니다.

각 컴포넌트는 하나의 명확한 책임만 가져야 합니다.

<!-- ❌ 나쁜 예: 너무 많은 책임 -->
<!-- UserDashboard.vue - 사용자 정보, 통계, 설정 등 모든 것을 처리 -->
<!-- ✅ 좋은 예: 책임 분리 -->
<!-- UserDashboard.vue - 레이아웃만 담당. components/ 의 컴포넌트는 임포트 없이 쓴다 -->
<template>
<div class="dashboard">
<UserProfile />
<UserStats />
<UserSettings />
</div>
</template>

Vue 공식 스타일 가이드에 따라 Props 케이싱을 일관되게 사용합니다. 워크스페이스는 vue/attribute-hyphenation(경고)으로 검사하고, 어노테이터는 검사하지 않습니다.

  • Props 선언: camelCase 사용
  • 템플릿에서 전달: kebab-case 사용
<template>
<!-- ✅ 좋은 예: kebab-case로 전달 -->
<MyComponent greeting-message="hello" :item-count="10" />
<!-- ❌ 피해야 할 예: camelCase로 전달 -->
<MyComponent greetingMessage="hello" :itemCount="10" />
</template>
<script setup lang="ts">
// Props 선언 시 camelCase
defineProps<{
greetingMessage: string
itemCount?: number
}>()
</script>

워크스페이스는 Tailwind CSS 유틸리티 클래스로 스타일을 주며, <style> 블록이 있는 컴포넌트는 일부입니다. <style> 블록이 필요하면 scoped 를 붙여 컴포넌트에 한정합니다(권장).

<template>
<button type="button" class="button-highlight rounded px-4 py-2 text-white">저장</button>
</template>
<style scoped>
/* 유틸리티 클래스로 표현하기 어려운 스타일만 둔다 */
.button-highlight {
transition: box-shadow 0.2s;
}
</style>
<template>
<button
aria-label="메뉴 열기"
:aria-expanded="isMenuOpen"
@click="toggleMenu">
<IconMenu />
</button>
<nav :aria-hidden="!isMenuOpen">
<!-- 메뉴 내용 -->
</nav>
</template>
  • 화면에 보이는 문구는 모두 i18n 으로 씁니다(권장).
  • 워크스페이스는 컴포넌트 문구를 <i18n> 블록(JSON 또는 YAML)에 한국어·영어를 함께 두고 useI18n({ useScope: 'local' }) 의 t 로 씁니다. 여러 화면이 함께 쓰는 문구는 공용 메시지 파일에 두고 $t 로 씁니다.
  • 메시지 키는 camelCase 로 씁니다(messageLog, cancelJobTitle). 한 단어는 소문자(status), 약어는 첫 글자만 대문자(dataUnitId)로 씁니다. 기존 코드에는 no_data 같은 snake_case 키가 일부 남아 있습니다.
<template>
<div>
<h1>{{ t('welcomeTitle') }}</h1>
<p>{{ t('welcomeDescription', { name: userName }) }}</p>
</div>
</template>
<script setup lang="ts">
defineProps<{ userName: string }>()
const { t } = useI18n({ useScope: 'local' })
</script>
<i18n lang="yaml">
ko:
welcomeTitle: 환영합니다
welcomeDescription: '{name}님, 안녕하세요'
en:
welcomeTitle: Welcome
welcomeDescription: 'Hello, {name}'
</i18n>

요약 체크리스트

  • 컴포넌트는 kebab-case 폴더 + PascalCase 파일(워크스페이스)
  • 기본 UI 컴포넌트는 components/ui/ 관례(접두사 없음)를 따름(워크스페이스)
  • 페이지/레이아웃 단일 루트 요소 보장
  • 동적 라우트/캐치올/그룹 구조 명확화
  • 컴포저블 use*/스토어 use*Store 일관성, 하위 폴더의 컴포저블·스토어는 경로를 적어 임포트
  • SFC 블록 순서 template → script → style → i18n
  • 서버 데이터는 TanStack Query + useAPI(), 화면에 계속 반영할 값은 useQuery 결과
  • 커밋 훅(lefthook)을 건너뛰지 않기 — CI 에서는 ESLint·Prettier 를 검사하지 않음
  • Pinia 반응성(storeToRefs) 준수

본 가이드는 워크스페이스(Nuxt 3) 프로젝트의 구조, 명명, 코드 스타일을 정리한 문서입니다. 강제 규칙의 정본은 각 저장소의 ESLint·Prettier 설정 파일이므로, 설정이 바뀌면 이 문서의 표도 함께 갱신합니다. 권장 규칙은 팀 합의와 리뷰를 통해 지속적으로 개선하세요.