TypeScript,Nuxtの環境構築をしてみる

2019/04/06

create-nuxt-appを使わないでTypeScript,Nuxtの環境構築をしてみます。

任意のプロジェクト名でディレクトリを作成、移動

mkdir nuxt-typescript 
cd nuxt-typescript 

package.json作成

npm init -y

scriptのとこにdevを追加

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nuxt"
  },

nuxtインストール

npm i --save nuxt

pagesディレクトリの作成

mkdir pages

pages/index.vueの作成

<template>
    <h1>Hello world!</h1>
</template>

npm run devでサーバーが立ち上がり、localhost:3000で「Hello World」が正常に表示されることを確認

npm run dev

ts-node、@nuxt/typescriptをインストール

npm i -D ts-node @nuxt/typescript

ルートにnuxt.config.tsとtsconfig.jsonを作成

nuxt.config.ts

import NuxtConfiguration from '@nuxt/config'

const config: NuxtConfiguration = {
};

module.exports = config

tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": "."
  }
}

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

npm i -D vue-property-decorator

ここまでで環境構築は完了です。

せっかく環境ができたので、少しTypeScriptで書いてみます。
ボタンが押されたらHello WorldをHello Nuxtに変えるだけのものです。

<template>
  <div>
     <h1>{{message}}</h1>
     <button v-on:click="handleClick">ボタン</button>
  </div>
</template>

<script lang="ts">
  import {Component, Vue, Emit} from 'vue-property-decorator'

  @Component({})
  export default class extends Vue {
    message: string = 'Hello World';

    @Emit()
    handleClick() {
      this.message = 'Hello Nuxt'
    }

  }
</script>

TypeScriptでのVueコンポーネントの書き方勉強中。。。