LoginSignup
10
8

More than 3 years have passed since last update.

既存のVueプロジェクトにTypeScriptを導入する

Posted at

TL;DR

  • 既存のVueプロジェクトにTypeScriptを導入したい際にやったことをまとめた
  • vue-clinuxtを利用したプロジェクトではない
  • extendではなくデコレータ方式で記述する

バージョン

  • webpack: 4.33.0
  • typescript: 3.5.3
  • vue-property-decorator: 8.2.1
  • ts-loader: 6.0.4
  • @typescript-eslint/parser: 1.12.0
  • @vue/eslint-config-typescript: 4.0.0
  • vue-eslint-parser: 6.0.4
  • ts-jest: 24.0.2

実際に導入する

Vue

関連モジュール

$ npm i -D typescript vue-property-decorator

型定義ファイル(d.ts)を作成する。

index.d.ts
declare module "*.vue" {
  import Vue from "vue";
  export default Vue;
}

Webpack

関連モジュールのインストール

$ npm i -D ts-loader

webpack.config.jsの設定

webpack.config.js
...
{
  test: /\.ts$/,
  loader: "ts-loader",
  exclude: "/node_modules/",
  options: {
    appendTsSuffixTo: [/\.vue$/]
  }
}
...

ESLint

関連モジュールのインストール

$ npm i -D @typescript-eslint/parser @vue/eslint-config-typescript vue-eslint-parser

.eslintrc.jsの設定

eslintrc.js
module.exports = {
  ...
  extends: [
    'plugin:vue/recommended',
    'eslint:recommended',
    '@vue/typescript'
  ],
  parser:  'vue-eslint-parser',
  parserOptions: {
    parser: '@typescript-eslint/parser',
    ecmaFeatures: {
      "legacyDecotators": true
    }
  },
  ...
}

Jest

関連モジュールのインストール

$ npm i -D ts-jest

jest.config.jsの設定

jest.config.js
module.exports = {
  moduleFileExtensions: ["js", "jsx", "json", "vue", "ts"],
  transform: {
    "^.+\\.vue$": "vue-jest",
    "^.+\\.(ts|tsx)$": "ts-jest"
  },
  transformIgnorePatterns: ["node_modules/"],
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/js/$1"
  },
  snapshotSerializers: ["jest-serializer-vue"],
  testMatch: ["**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)"],
  testURL: "http://localhost/",
  setupFiles: [
    "<rootDir>/tests/unit/jest-env.js"
  ],
  globals: {
    "ts-jest": {
      "tsConfigFile": "tsconfig.json"
    }
  },
  watchPlugins: [
    "jest-watch-typeahead/filename",
    "jest-watch-typeahead/testname"
  ],
  "collectCoverage": true,
  "collectCoverageFrom": ["src/js/**/*.{js,vue}"]
};

型定義ファイル

使ってるライブラリの型定義ファイル(@types/〇〇)をインストールしておく。

TypeScriptの設定ファイル

tsconfig.jsonを作成する。

tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "es2015",
    "strict": false,
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "es2019",
      "esnext",
      "dom"
    ],
    "resolveJsonModule": true
  }
}

10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8