JHyeok

TypeScript로 Nuxt 개발하기 - 2

January 16, 2020☕️ 2 min read

TypeScript로 Nuxt 개발하기 시리즈
TypeScript 환경으로 Nuxt 개발
TypeScript Lint, Jest 환경 구성

TypeScript로 Nuxt 개발하기 시리즈에 사용된 소스코드는 여기에서 확인할 수 있다.

이전 시리즈에서는 TypeScript 환경에서 Nuxt를 개발하는 환경을 구성해보았다. 이번에는 코드 스타일을 검사하는 ESLint와 코드를 예쁘게 해주는 Prettier, 테스트 라이브러리인 Jest를 TypeScript 환경에서 사용하는 방법에 대해 설명한다.

ESLint 적용

아마 현재 프로젝트에는 ESLint가 활성화되어 있을 것인데, 이것을 TypeScript용으로 구성해주면 된다. TSLint를 사용하지 않는 이유는 TSLint가 이제 업데이트를 중단했기 때문이다. 관련 내용은 여기에서 확인할 수 있다.

먼저 @nuxtjs/eslint-config를 지우고 @nuxtjs/eslint-config-typescript를 설치한다.

yarn remove @nuxtjs/eslint-config
yarn add -D @nuxtjs/eslint-config-typescript

.eslintrc.js를 수정한다.

module.exports = {
  extends: [
    '@nuxtjs/eslint-config-typescript'
  ]
}

혹시 .js 파일이어서 javascript를 사용하는 것에 거부감이 있다면 .json 파일로 생성해도 된다. 필자는 100% TypeScript를 사용하고 싶어서 아래처럼 .json 파일로 만들었다.

.eslintrc.json

{
  "root": true,
  "env": {
    "browser": true,
    "node": true
  },
  "parserOptions": {
  },
  "extends": [
    "@nuxtjs/eslint-config-typescript"
  ],
  "rules": {
  }
}

마지막으로 Lint 스크립트를 사용할 수 있도록 package.json을 수정한다.

"lint": "eslint --ext .ts,.js,.vue ."

주의할 점은 parserOptionsbabel-eslint가 있다면 제거해주어야 한다. 그리고 Lint에 사용되는 규칙들을 수정하거나 재정의하려면 여기를 참고하면 된다.

eslint-config-typescript/index.js

module.exports = {
  extends: [
    '@nuxtjs'
  ],
  plugins: ['@typescript-eslint'],
  parserOptions: {
    parser: '@typescript-eslint/parser'
  },
  rules: {
    '@typescript-eslint/no-unused-vars': ['error', { args: 'all', argsIgnorePattern: '^_' }]
  }
}

위에서 설치한 @nuxtjs/eslint-config-typescript를 확인해보면 내부적으로 @typescript-eslint/parser를 parser로 사용하기 때문이다.

Prettier 적용

prettier와 prettier를 ESLint에서 실행할 수 있는 패키지를 설치한다.

yarn add -D prettier eslint-config-prettier eslint-plugin-prettier

패키지 설치가 끝났다면 .eslintrc.json을 수정한다. extends에 prettier 관련 옵션들을 설정하고 plugins에 prttier를 설정한다.

{
  "root": true,
  "env": {
    "browser": true,
    "node": true
  },
  "parserOptions": {
  },
  "extends": [
    "@nuxtjs/eslint-config-typescript",
    "plugin:nuxt/recommended",
    "plugin:prettier/recommended",
    "prettier",
    "prettier/vue"
  ],
  "plugins": [
    "prettier"
  ],
  "rules": {
  }
}

prettierr의 옵션을 설정할 수 있는 .prettierrc를 생성한다.

{
  "semi": false,
  "arrowParens": "always",
  "singleQuote": true,
  "endOfLine": "auto"
}

이제 ESLint를 사용할 때, 코드 스타일을 예쁘게 바꿔주는 Prettier도 같이 동작하게 된다.

Jest

Jest를 TypeScript 환경에서 개발하기 위해서는 ts-jest와 @types/jest를 설치한다.

yarn add -D ts-jest @types/jest

tsconfig.json를 수정한다.

{
  "compilerOptions": {
    "types": ["@types/jest"]
  }
}

jest.config.js가 ts확장자를 읽을 수 있도록 수정한다. jest.config.js를 사용하지 않고 package.json에 jest 옵션을 추가해서 사용해도 된다.

jest.config.js

module.exports = {
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^~/(.*)$': '<rootDir>/$1'
  },
  transform: {
    '^.+\\.ts?$': 'ts-jest',
    '.*\\.(vue)$': 'vue-jest'
  },
  moduleFileExtensions: ['ts', 'js', 'vue', 'json']
};

또는

package.json

  "jest": {
    "moduleNameMapper": {
      "^@/(.*)$": "<rootDir>/$1",
      "^~/(.*)$": "<rootDir>/$1",
      "^vue$": "vue/dist/vue.common.js"
    },
    "moduleFileExtensions": ["ts", "js", "vue", "json"],
    "transform": {
      "^.+\\.ts$": "ts-jest",
      ".*\\.(vue)$": "vue-jest"
    },
    "collectCoverage": true,
    "collectCoverageFrom": [
      "<rootDir>/components/**/*.vue",
      "<rootDir>/pages/**/*.vue"
    ]
  },

vue-shim.d.ts를 추가하여 .vue파일에 대한 유형을 제공해야 한다. .vue파일에 대해서 이제 TypeScript가 인식할 수 있다.

// vue-shim.d.ts
declare module "*.vue" {
  import Vue from 'vue'
  export default Vue
}

마지막으로 test/Logo.spec.jstest/Logo.spec.ts로 확장자를 변경하고 yarn test로 Jest를 실행해서 테스트가 정상적으로 완료되는지 확인한다.

yarn run v1.21.1
$ jest
 PASS  test/Logo.spec.ts
  Logo
    √ is a Vue instance (14ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.679s, estimated 16s
Ran all test suites.
Done in 4.60s.

마치며

Nuxt.js 2.9 버전 이후로 TypeScript를 적용하는 방법이 기존과는 조금 달라졌다. 기존 한국어 자료를 바탕으로 진행을 하다가 진행이 막혀서 직접 공식 가이드를 보고 적용을 하면서 방법이 많이 달라진 것을 느끼고 TypeScript로 Nuxt 개발하기를 작성했다.

Reference


JHyeok

JaeHyeok Kim

Written by JaeHyeok Kim
GitHubMedium

© 2019 - 2024, Built with Gatsby