LoginSignup
52
44

More than 3 years have passed since last update.

Nuxt.jsでTypeScriptを使うための手順

Last updated at Posted at 2019-05-08

はじめに

Nuxt.jsがTypeScriptを公式サポートしているのですが、公式サイトに記載されている手順だと不足していたので、動作確認できるところまでの手順をまとめておきます。

Nuxt.js | TypeScript サポート

前提条件

  • nuxtのバージョンが2.4.0以上であること
  • ESLintのバージョンが5であること。(2019/8/9追記)

バージョン確認方法

# プロジェクトルートで以下のコマンドを実行
$ ./node_modules/nuxt/bin/nuxt.js -v

TypeScriptの利用手順

@nuxt/typescriptモジュールをインストール

$ npm i -D @nuxt/typescript

tsconfig.jsonファイルを作成

$ echo "{}" > tsconfig.json

configファイル名変更

変更前)nuxt.config.js
変更後)nuxt.config.ts

nuxt.config.tsの修正

nuxt.config.ts
- import pkg from './package'
+ const pkg = require('./package')

ts-nodeのインストール

$ npm i -D ts-node

vue-property-decoratorのインストール

$ npm i -S vue-property-decorator

ESLintの利用手順

Lintを行う必要がある場合のみ、以下の手順を行ってください。

eslint-pluginのインストール

$ npm i -D @typescript-eslint/eslint-plugin @typescript-eslint/parser

.eslintrc.jsの修正

.eslintrc.js
- parser: 'babel-eslint'
+ parser: '@typescript-eslint/parser'

+ plugins: [
+   '@typescript-eslint'
+ ],

※ Prettierを利用している場合は、最初からpluginが用意されてますので、@typescript-eslintを追記する形になります。(2019/8/9追記)

.eslintrc.js
plugins: [
    'prettier',
    '@typescript-eslint'
]

package.jsonの修正

package.json
- "lint": "eslint --ext .js,.vue --ignore-path .gitignore .",
+ "lint": "eslint --ext .ts,.js,.vue --ignore-path .gitignore .",

Lint実行

$ npm run lint

動作確認

Nuxtプロジェクトを作成した際に元々あるファイルをTypeScriptで書き直したあと、動作確認を行います。

pages/index.vueを編集

変更前
<script>
import Logo from '~/components/Logo.vue'

export default {
  components: {
    Logo
  }
}
</script> 
変更後
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'

@Component({
  components: {
    Logo: () => import('~/components/Logo.vue')
  }
})
export default class Index extends Vue {}
</script>

サーバ起動

$ npm run dev

http://localhost:3000 にアクセスして、画面が表示されるか確認してください。
正しく表示されたら、TypeScriptのセットアップは完了です。

52
44
1

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
52
44