はじめに
Nuxtの2.5.xだとnuxt-ts
を使う必要がなくなってとても簡単になったので手順まとめ。
手順
新規プロジェクトの作成
create-nuxt-app
で新規プロジェクトを作成。
今回はESLintの設定までやるのでLinter / Formatter
とPrettier
を追加しておく。なおパッケージマネージャーはお好みで(今回はyarn
)。
$ npx create-nuxt-app nuxt-ts-sample ? Project name nuxt-ts-sample ? Project description My fantabulous Nuxt.js project ? Use a custom server framework none ? Choose features to install Linter / Formatter, Prettier ? Use a custom UI framework none ? Use a custom test framework none ? Choose rendering mode Single Page App ? Author name shuhei.yamashita ? Choose a package manager yarn To get started: cd nuxt-ts-sample yarn run dev To build & start for production: cd nuxt-ts-sample yarn run build yarn start $ cd nuxt-ts-sample
これでプロジェクトの作成は完了。
パッケージを追加
前まではnuxt
を除去してnuxt-ts
を入れていたが、今は@nuxt/typescript
を追加すればOK。
あとついでに@typescript-eslint/eslint-plugin
とデコレーターのnuxt-property-decorator
を追加する。
$ yarn add -D @nuxt/typescript nuxt-property-decorator @typescript-eslint/eslint-plugin
tsconfig.jsonを追加
tsconfig.json
があることでプロジェクトにTypeScriptが使われていると判断される。必要な設定は自動で追加されるので自分で設定内容を作っておく必要はない。設定値なしで作成して一度起動しておく。
$ echo "{}" > tsconfig.json $ yarn run dev # 設定値追加が目的なので起動後は終了していい
自動で設定される設定値はここ参照。
nuxt.js/index.js at dev · nuxt/nuxt.js · GitHub
.eslintrc.jsの内容を修正
parserOptions: { - parser: 'babel-eslint' + parser: '@typescript-eslint/parser' }, extends: [ '@nuxtjs', 'plugin:nuxt/recommended' ], plugins: [ + '@typescript-eslint', 'prettier' ], // add your custom rules here rules: { }
Nuxtの設定ファイルをTypeScriptに変更
この状態で動くのだが、せっかくなのでnuxt.config.js
をnuxt.config.ts
にして余計なjsファイルを減らしておく。
mv nuxt.config.js nuxt.config.ts
そしてwebpack
の型定義が必要になるのでパッケージを追加し、tsconfig.json
にも追記を行う。
$ yarn add @types/webpack
"types": [
"@types/node",
+ "@types/webpack",
"@nuxt/vue-app"
]
あとはnuxt.config.ts
の内容を修正。まずはimportの指定を修正。
-import pkg from './package' +import { Configuration } from 'webpack' +import { Context } from '@nuxt/vue-app' +import pkg from './package.json'
あとはWebpackの拡張設定であるextend
を修正。
- extend(config, ctx) { + extend(config: Configuration, ctx: Context) { // Run ESLint on save - if (ctx.isDev && ctx.isClient) { + if (config.module && ctx.isDev && ctx.isClient) { config.module.rules.push({ enforce: 'pre', test: /\.(js|vue)$/,
ただこのままだとpackage.json
のimportが怒られるのでtsconfig.json
でresolveJsonModule
を設定しておく。
"esModuleInterop": true,
"experimentalDecorators": true,
+ "resolveJsonModule": true,
"allowJs": true,
"sourceMap": true,
"strict": true,
pages/index.vueをTypeScript指定にする
-<script> +<script lang="ts"> +import { Component, Vue } from 'nuxt-property-decorator' import Logo from '~/components/Logo.vue' -export default { +@Component({ components: { Logo } -} +}) +export default class extends Vue {} </script>
起動してみる
特に問題なく設定されているならこれでちゃんと起動するはず。
$ yarn run dev