Vue 2.5 + TypeScript 3.0 を Parcel でビルドする


はじめに

Parcel で Vue + TypeScript のビルドをしてみようと試してみたら思いのほか簡単だったので、手順をメモします。

同じようなことを以前試したときはなかなかうまくいかなかったのですが、Parcel 自体のアップデートで改善されたようです。

今回は Windows 7 64bit に node v8.9.3 をインストールしている環境で試しました。おそらく Mac 等他の環境でも同様に動作すると思います。

package.json を用意する

プロジェクト用のディレクトリを作って package.json を作ります。

$ mkdir parcel-vue-ts
$ cd parcel-vue-ts
$ npm init -y
$ npm i -D parcel-bundler

実行すると以下のような package.json が出来上がります。

{
  "name": "parcel-vue-ts",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "parcel-bundler": "^1.9.7"
  }
}

scriptsstart という名前でスクリプトを登録します。

  "scripts": {
    "start": "parcel index.html",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

index.html は次の章で作ります。

HTMLファイルを作る

以下の内容を index.html という名前で保存します。

<html>
<body>
  <div id="app"></div>
  <script src="./main.ts"></script>
</body>
</html>

dev#app の下に Vue のインスタンスをマウントします。

TypeScriptファイルを作る

以下の内容を main.ts という名前で保存します。

import Vue from 'vue';
import App from './App.vue';

new Vue({
  el: '#app',
  render: h => h(App)
});

App.vue はこのあと作成する Vue のコンポーネントです。

Vue ファイルを作る

シンプルなアップダウンカウンタを作りました。

<template>
  <section>
    <p>{{count}}</p>
    <button @click="addCount(1)">UP</button>
    <button @click="addCount(-1)">DOWN</button>
  </section>
</template>

<script lang="ts">
export default {
  data () {
    return { count: 0 };
  },
  methods: {
    addCount(amount: number): void {
      this.count += amount;
    }
  }
};
</script>

ビルドする

ここまで用意してシェルで以下のように入力します。

$ npm start

初回は必要な依存関係 (Vue.js や TypeScript) をインストールするために時間がかかります。

ウェブブラウザで画面に表示されるアドレス (通常は http://localhost:1234) にアクセスすると次のような画面が表示され、ボタンをクリックすると表示される数値の価が上下します。

この時点で package.json は以下のようになりました。 (執筆時時点)

{
  "name": "parcel-vue",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "parcel index.html"
  },
  "author": "",
  "license": "UNLICENSED",
  "devDependencies": {
    "@vue/component-compiler-utils": "^2.1.0",
    "parcel-bundler": "^1.9.7",
    "typescript": "^3.0.1",
    "vue-template-compiler": "^2.5.17"
  },
  "dependencies": {
    "vue": "^2.5.17",
    "vue-hot-reload-api": "^2.3.0"
  }
}

まとめ

Parcel を使って Vue 2.5 + TypeScript 3.0 のプロジェクトをビルドしてみました。意外と簡単に利用できたので、特にちょっとしたプロトタイプを作りたいと思ったときなど、便利に活用できそうです。