Vue + Nuxt + Typescript

Vue + Nuxt + Typescript

Vue + Nuxt + Typescript

프로젝트에 vue + nuxt + typescript 세팅하는 데 애를 먹었던 적이 있어서 포스팅을 한다.
구글링을 해보면 nuxt에 typescript를 추가하는 글이 많이 보이는 데 최대한 최신의 글을 참고해야 한다. 그렇지 않으면 에러가 나거나 호환이 되지 않을 수가 있다. 나도 이 문제 때문에 하루를 낭비했다. 내가 참고했던 사이트는 아래에 남긴다.
  1. Nuxt 프로젝트 추가
    vue init nuxt-community/starter-template <project-name>
    
    디펜던시 설치
    cd <project-name>
    npm install
    
    프로젝트 실행
    npm run dev
    
    localhost:3000 접속
  2. Typescript 추가
    yarn add --dev @nuxt/typescript-build
    OR
    npm install --save-dev @nuxt/typescript-build
    
    nuxt.config.js에 buildModules 항목 추가
    export default {
      buildModules: ['@nuxt/typescript-build']
    }
    
    tsconfig.json 파일 추가
    {
      "compilerOptions": {
        "target": "esnext",
        "module": "esnext",
        "moduleResolution": "node",
        "lib": [
          "esnext",
          "esnext.asynciterable",
          "dom"
        ],
        "esModuleInterop": true,
        "allowJs": true,
        "sourceMap": true,
        "strict": true,
        "noEmit": true,
        "baseUrl": ".",
        "paths": {
          "~/*": [
            "./*"
          ],
          "@/*": [
            "./*"
          ]
        },
        "types": [
          "@types/node",
          "@nuxt/types"
        ]
      },
      "exclude": [
        "node_modules"
      ]
    }
    
    여기까지 추가하고, 다시 npm run dev로 실행해보면 에러가 날 것이다.
  3. 에러 처리
    • experimentalDecorators 관련 에러
    "experimentalDecorators":  true
    
    tsconfig.json에 위의 설정 코드를 추가하면 된다. 그래도 에러가 난다면 에디터를 껐다가 다시 싱행하면 에러 해결!
    • Please use export @dec class instead 에러
    {
      parserOptions: {
        ecmaFeatures: {
          legacyDecorators: true
        }
      }
    }
    
    .eslintrc.js에서 해당 내용을 찾아 수정해주면 에러 해결!
  4. 컴포넌트 수정 및 vue-property-decorator install
    <script lang="ts">
    import { Vue, Component } from  'vue-property-decorator'
    import { Mutation, Action } from  'vuex-module-decorators'
    import  AppLogo  from  '~/components/AppLogo.vue'
    
    @Component({
     components: {
      AppLogo
     }
    })
    
    export default class IndexPage  extends Vue { }
    </script>
    
    컴포넌트들은 위의 같은 형태로 수정해주면 된다. (layout 폴더 아래에 있는 파일은 DefaultLayout 이름으로, component 폴더 아래에 있는 파일은 LogoComponent 이런식으로 네이밍을 해주면 훨씬 더 알아보기 쉽다.)

참고

댓글

가장 많이 본 글