똑같은 삽질은 2번 하지 말자

Nuxt3 vol.1 본문

카테고리 없음

Nuxt3 vol.1

곽빵 2022. 12. 10. 20:44

개요

Nuxt 3를 이용해 프로젝트를 시작하기 전에 공식 문서를 읽고 특징과 달라진 점을 정리하고자 한다.

https://nuxt.com/

 

Nuxt: The Intuitive Web Framework

Global Maintainers Summit Event 2021 globalmaintainersummit.github.com

nuxt.com

 

프로젝트 시작하기

주의! node version >= 16.11

npx nuxi init heewon-blog-admin

Nuxt3의 특징? 달라진 점?

1. Auto Import

import XXComponent from "@/components/XXComponent" 를 안해도 된다. 자동으로 컴포넌트가 import 되므로 위의 코드를 안 적어도 된다는 것 !

components/Button.vue

<template>
  <button>Btn</button>
</template>

App.vue

<!-- import를 안해도 Button컴포넌트를 사용할 수 있다. -->
<template>
  <Button />
</template>

이에 대한 규칙 같은걸 조금 알아보자.

 

1-1. 지연로딩, Lazy Load

prefix로 Lazy를 추가하면 지연로딩을 지원해 준다고 한다.

<template>
  <div>
    <LazyButton />
  </div>
</template>

1-2. Nested된 컴포넌트의 경우는?

atoms/Button.vue 를 사용할 때는 이렇게 하면 된다.

<template>
  <div>
    <AtomsButton />
  </div>
</template>

1-3. 그냥 import를 써서 명시적으로 하고 싶은 경우에는?

import { Btn } from '#button';

 

2. Nuxt는 더 이상 Vuex 통합을 제공하지 않는다.

보통 store라는 디렉터리를 만들면 자동으로 vuex가 적용되어 store를 사용할 수 있었지만 그 부분이 이제 없어진 것이다. 공식적인 Vue 권장 사항은 Nuxt 모듈을 통해 Nuxt 지원이 내장된 pinia를 사용하는 것

https://nuxt.com/docs/migration/configuration#vuex

 

Migrate to Nuxt 3: Configuration

The starting point for your Nuxt app remains your nuxt.config file. You should migrate to the new defineNuxtConfig function that provides a typed configuration schema.Nuxt 2export default { // ...}Copy to clipboardNuxt 3export default defineNuxtConfig({ //

nuxt.com

 

3. route별로 다양한 렌더링 방식을 지원한다.

react처럼 페이지 별로 SSR SSG SPA 방식으로 렌더링 되도록 개발할 수 있으면 좋겠다~ 라고 생각한 기능인데 Nuxt 3에서 이렇게 대응 해 주었다!! 기존의 Nuxt 2는 렌더링 방식을 전체의 범위에서만 정할 수 있었지만, 이제는 route 별로 렌더링 방식을 정할 수 있다.

export default defineNuxtConfig({
  routeRules: {
    // Static page generated on-demand, revalidates in background
    '/blog/**': { swr: true },
    // Static page generated on-demand once
    '/articles/**': { static: true },
    // Set custom headers matching paths
    '/_nuxt/**': { headers: { 'cache-control': 's-maxage=0' } },
    // Render these routes with SPA
    '/admin/**': { ssr: false },
    // Add cors headers
    '/api/v1/**': { cors: true },
    // Add redirect headers
    '/old-page': { redirect: '/new-page' },
    '/old-page2': { redirect: { to: '/new-page', statusCode: 302 } }
  }
})

https://nuxt.com/docs/guide/concepts/rendering 

 

Rendering Modes · Nuxt Concepts

Both the browser and server can interpret JavaScript code to render Vue.js components into HTML elements. This step is called rendering. Nuxt supports both client-side and universal rendering. The two approaches have pros and cons that we will cover in thi

nuxt.com

 

4. vite와 webpack5 번들러 지원

Nuxt 3는 디폴트 번들러로 vite를 사용하고 있는데 이를 webpack5 로 바꿀 수도 있다. 고속 번들러들을 제공함으로써 개발자 경험의 향상을 시켜준다.

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
  vite: {},
  webpack: {},
})

 

밑의 글은 webpack 5+ esbuild의 강력함을 쉽게 알 수 있게 정리한 포스트 입니다. 

 

환상적인 케미, Webpack + ESBuild - 오픈소스컨설팅 테크블로그

빌드 속도를 향상시키기 위해 ESBuild를 사용해 Webpack을 Customizing 해보자. 제품 빌드 속도 6분에서 4분으로 단축시킨 경험기.

tech.osci.kr

 

5. Nitro

Nuxt 3는 새로운 서버 엔진인 Nitro로 구동된다.

  • Node.js, 브라우저, 서비스 작업자 등에 대한 크로스 플랫폼 지원.
  • 즉시 사용 가능한 서버리스 지원.
  • API 경로 지원.
  • 자동 코드 분할 및 비동기 로드 청크.
  • 정적 + 서버리스 사이트용 하이브리드 모드.
  • 핫 모듈 재로딩이 있는 개발 서버

아직까진 이 Nitro에 대해서 확 와닿지 않아서 어떤식으로 활용해 나갈지는 잘 모르겠지만, server middleware가 개선된 건 좋은것 같다. 이전에 express + server middleware로써 간단한 내부 api server를 만들어 봤었는데 갑자기 HMR이 무한으로 되거나 하는 에러들이 많았던거 같은데.. 이제는 없어지는건가?

https://nuxt.com/docs/guide/directory-structure/server

 

server/ · Nuxt Directory Structure

Nuxt automatically scans files inside the ~/server/api, ~/server/routes, and ~/server/middleware directories to register API and server handlers with HMR support. Each file should export a default function defined with defineEventHandler(). The handler can

nuxt.com

 

 

부록. Nuxt 3에서 환경변수 관리하기 (runtimeConfig)

nuxt.config.ts

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
  runtimeConfig: {
    apiKey: 'exam',
    public: {
      publicApiKey: '345',
    },
  },
})

.env

NUXT_API_KEY: thisisApiKey

코드로 말하자면, public으로 nested된 친구 이외의 변수들은 전부 client side에서는 접근할 수 없다. 그리고 runtimeConfig.apiKey는 .env 파일에 NUXT_API_KEY: 가 존재할 경우 덮어쓰기 되어서 client side에서도 환경변수에 접근할 때 runtimeConfig를 활용할 수도 있다.

<script setup lang="ts">
const runtimeConfig = useRuntimeConfig()
console.log(runtimeConfig)
</script>

// serverSide
{                                                                                                                                                                     15:06:20
  app: { baseURL: '/', buildAssetsDir: '/_nuxt/', cdnURL: '' },
  nitro: { routeRules: { '/__nuxt_error': [Object] }, envPrefix: 'NUXT_' },
  public: { publicApiKey: '345' },
  apiKey: 'thisisApiKey'
}

// clientSide
{                                                                                                                                                                     15:06:20
  app: { baseURL: '/', buildAssetsDir: '/_nuxt/', cdnURL: '' },
  public: { publicApiKey: '345' },
}

이전에는 .env.prod .env.dev와 같이 환경별로 여러개의 환경변수 파일을 만들어 관리하는 방식이 있었는데 이걸 runtimeConfig에 적용해서 활용하려고 하면 script를 조금 수정해 주면 된다.

{
  "private": true,
  "scripts": {
    "build": "nuxt build",
    "start": "nuxt --dotenv .env.prod start",
    "dev": "nuxt --dotenv .env.local dev",
    "generate": "nuxt --dotenv .env.local generate",
    "preview": "nuxt --dotenv .env.prod preview",
    "postinstall": "nuxt prepare"
  },
  "devDependencies": {
    "nuxt": "3.0.0"
  }
}

원하는 command에 --dotenv .env.prod를 같이 끼워주면 환경별로 읽어들이는 환경변수 파일을 조정할 수 있다.

만약 해당 환경파일이 없다면 덮어쓰기는 안되고 기존에 있던 값이 그대로 셋팅된다. --dotenv를 지정안할시에는 .env가 자동 적용된다.

 

그리고 nuxt 디폴트 번들로로써 vite를 쓰고 있는데 vite의 import.meta.env를 nuxt.config.ts에 연계해서 사용하고 싶었지만, import.meta를 사용하는 곳이 nuxt.config.ts가 되므로 모듈로써? 인식이 안되어 사용할 수 없다고 에러가 났는데 이를 나중에 한번 깊게 파봐야 겠다. 참고로 vite도 dotenv를 사용하고 있다.

https://vitejs.dev/guide/env-and-mode.html

 

Vite

Next Generation Frontend Tooling

vitejs.dev

https://www.ragate.co.jp/blog/articles/12663

 

Nuxt 3はなぜ優秀?VueJSの開発を快適・効率的にするフレームをNuxt3実装者がまとめます😎 | Ragate

こんにちは!Nuxt では最近、最新バージョンの Nuxt3 の RC 版が現在公開され、2022年6月には正式リリースが予定されています。Nuxt3 は RC 版が登場したのに伴い、わたしたちも早速

www.ragate.co.jp

...작성중

Comments