
※ 이 글은 그냥 글쓴이같이 급한 사람들이 빠르게 가져가 쓰기를 바라면서 작성했습니다.
vue로 이것저것 만들다 보면 import를 하기 귀찮은 시기가 온다.
그걸 해결하기 위해 2가지의 라이브러리를 가져왔다.
https://www.npmjs.com/package/unplugin-vue-components
https://www.npmjs.com/package/unplugin-auto-import
이 두 가지의 라이브러리이다.
npm install unplugin-auto-import unplugin-vue-components
들어가기 귀찮으면 위 명령어를 터미널에 입력을 하든
아래 코드를 package.json에 입력 후 -> 저장 -> npm i를 실행하면 됩니다.
"devDependencies": {
"unplugin-vue-components": "^0.26.0", // 버전은 다를수 있습니다.
"unplugin-auto-import": "^0.17.5", // 버전은 다를수 있습니다.
}
먼저 vite.config.ts 파일을 설정할 것이다.
(현재 라이브러리 쓰는데 필요 없는 코드는 삭제했습니다. 그래도 depth를 그대로 놔둘게요)
// Vue 등의 API 자동 임포트 플러그인
import AutoImport from 'unplugin-auto-import/vite'
// Vue 컴포넌트를 자동으로 탐색 및 등록하는 플러그인
import Components from 'unplugin-vue-components/vite'
// https://vite.dev/config/
export default defineConfig({
plugins: [
...
// 자동 임포트 플러그인 설정
AutoImport({
// 자동 import할 api가 있으면 추가 하시면 됩니다. ex)pinia,vue-router,vue-i18n 등등
imports: ['vue'],
eslintrc: {
enabled: false, // ESLint 설정 파일 자동 생성 비활성화
filepath: './.eslintrc-auto-import.json', // ESLint 설정 파일 경로
globalsPropValue: true, // 글로벌 변수의 속성 값으로 "true"를 설정
},
}),
// 컴포넌트 자동 등록 플러그인 설정
Components({
extensions: ['vue'],
include: [/\.vue$/, /\.vue\?vue/],
dirs: ['src/components/', 'src/layout'],
}),
],
})
vite 설정은 끝났다. 그냥 저장하면 이미지와 같이 그냥 생긴다.
그럼 이제 component를 2개를 만들어 보겠습니다.
src/components/CmHeaderTitle.vue
src/components/common/CmBodyMessage.vue
와 같이 만들었습니다. 아래는 각 코드입니다.
//CmHeaderTitle.vue
<script setup lang="ts">
const title = ref('Hello auto import and components') //'vue'에서 자동 임포트된 ref
</script>
<template>
<div>
<h1>{{ title }}</h1>
</div>
</template>
<style scoped></style>
//CmBodyMessage.vue
<script setup lang="ts"></script>
<template>
<div>
<h1>end!!! 🥳🥳🥳🥳</h1>
</div>
</template>
<style scoped></style>
와 같이 코드를 작성 후 App.vue에 아래와 같이 작성을 하면!!!
<template>
<div>
<cm-header-title></cm-header-title>
<cm-body-message></cm-body-message>
</div>
</template>
<script setup lang="ts"></script>
<style scoped></style>
잘 나오네요!! 네 끝입니다.
네 그냥 끝내기 아쉬우니 필요한 사람만 보세요.
AutoImport와 Components 플러그인의 설정에 대한 상세 설명입니다.
eslintrc: 자동 임포트 된 api를 eslint에서 인식하도록 설정
- enabled: true로 설정 시 eslint 설정 파일이 생성됩니다.
(※ 만약 false로 하면 eslint 설정 파일 생성 기능이 비활성화되어 정의되지 않은 변수 오류가 발생할 수 있음
근데 TypeScript 는 enabled: false로 두고 no-undef 규칙을 비활성화해도 충분히 동작 가능!!!! 이유는 컴파일단계에서 이미 TypeScript가 자동 임포트된 API를 확인해서 그렇습니다.)- filepath: 생성할 eslint 설정 파일 경로.
- 기본값: ./.eslintrc-auto-import.json.
- globalsPropValue: 생성된 eslint 설정 파일에서 글로벌 변수를 readonly 또는 true로 설정.
( 위와 동일)
extensions: 탐색할 컴포넌트 파일의 확장자를 지정
- 설명: 탐색할 컴포넌트 파일의 확장자를 지정.
- 기본값: ['vue']
- 사용 가능 값: ['vue', 'jsx']: Vue 및 JSX 파일 탐색.
include: 컴포넌트로 처리할 파일을 지정하는 정규식
기본값: /.vue$/: .vue 확장자를 가진 파일. /.vue\?vue/: Vue SFC(Single File Component)로 처리되는 파일.
dirs: 컴포넌트를 탐색할 디렉터리 경로
설정된 값:'src/components/': 컴포넌트를 기본적으로 저장하는 폴더.'src/layout': 레이아웃 관련 컴포넌트를 저장하는 폴더.