かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

Vue.js 勉強メモ 3 (TypeScript で!!)

色々勉強する前に TypeScript で確認出来るようにしておきたい

とりあえず簡単な方法は Vue.js の CLI を使って TypeScript を有効にしたプロジェクトをスタート地点とするみたいなので、それでやっていこうと思う。

プロジェクト作っていらないものを削除

vue create ts-lab

とか打ち込んで TypeScript だけを有効化したプロジェクトを作る。

src フォルダーの下の .vue ファイルを丸っと削除。

ハローワールドを TypeScript で

public/index.html を以下のように書き換え。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title>ts-lab</title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but ts-lab doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app">{{ message }}</div>
    <!-- built files will be auto injected -->
  </body>
</html>

div の中に {{ message }} を足してます。そして src/main.ts を以下のように書き換え。

import Vue from 'vue'

const app = new Vue({
  el: '#app',
  data: {
    message: 'Hello TypeScript',
  },
});

最後に runtimeCompiler のオプションを true にしないといけない。これは今回のように実行時にコンパイルされるテンプレートがある場合には必須みたいですね。

cli.vuejs.org

これを設定しないと以下のようなメッセージがブラウザーのコンソールに出る。

[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

(found in <Root>)

ということで vue.config.js をプロジェクトルートに作って中身を以下のようにします。

module.exports = {
    runtimeCompiler: true,
}

そして、npm run serve とすれば開発サーバーが立ち上がってブラウザーで URL を開くと以下のように結果が確認できます。

f:id:okazuki:20190219170604p:plain

まとめ

ということで TypeScript に読み替えながら Vue.js のドキュメントを読みながら試すための環境が整いました。 おおまかな手順としては…

  • vue-cli で TypeScript のプロジェクトを作る
  • .vue を全部削除
  • vue.config.js で runtimeCompiler を true にする
  • main.ts を編集
  • npm run serve して Let's go.

ということで次からはドキュメントを読みながら遊んでいこうと思います。