LoginSignup
13
8

More than 5 years have passed since last update.

VueでTypeScriptを使う時のテンプレートを作った

Last updated at Posted at 2016-02-14

投稿時点のバージョン

Vue.js: v1.0.16
TypeScript: 1.7.5
vue-cli: v1.3.0
vue-loader: v8.0.0

概要

 Vue.jsは最近(2015年末ごろ?)、Vueを使ったWebアプリのひな形をかんたんに作成できるCLIツール(vue-cli) の提供をはじめました。

 このツールは自作のテンプレートを利用できるようになっていますので、TypeScriptを使ったテンプレートを作ってみました。
https://github.com/AbeHaruhiko/vue-webpack-typescript

 公式のテンプレートは下記の4種類です。一番上のテンプレートをForkして作りました。

Get Started

$ npm install -g vue-cli
$ vue init AbeHaruhiko/vue-webpack-typescript my-project
$ cd my-project
$ npm install
$ tsd install
$ npm run dev

 ※ 公式のテンプレートと違いtsd install が必要なのでお忘れなく!!

背景

 公式のテンプレート(vue-loaderを使う)では、*.vue ファイルで <script lang="ts"> としても、 下記のようなエラーになり、トランスパイルに失敗します。

ERROR in ./~/ts-loader!./~/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue
Module build failed: Error: Could not find file: '/path/to/peoject/src/App.vue'.
    at getValidSourceFile (/path/to/peoject/node_modules/typescript/lib/typescript.js:44463:23)
    at Object.getEmitOutput (/path/to/peoject/node_modules/typescript/lib/typescript.js:47595:30)
    at Object.loader (/path/to/peoject/node_modules/ts-loader/index.js:406:34)
 @ ./src/App.vue 3:17-107

 webpack.base.conf.jstranspileOnly とすることでエラーは解消できますが、肝心の静的解析が行われなくなるのでTypeScript最大のメリットが失われます。

webpack.base.conf.js
  ts: {
      transpileOnly: true
  }

[参考] https://github.com/vuejs/vue-loader/issues/109

 そこで、*.vue (vue-loader)の使用はあきらめて、*.tsを ts-loaderで読み込んで使用します。その際 vue-class-component を使用します。同様に*.htmlはhtml-loader、*.cssはstyle-loaderで読み込みます。

注意

 *.vue ファイルを使ったコンポーネントと違い、html, ts, css に分断されてしまいます。ひとつのコンポーネントを1ファイルで扱えるvue-loaderのメリットが失われますが、それぞれlintによる静的解析が利用できるなど、メリットもあります。

 なお htmlこのサンプル のようにdecoratorの引数として、ts ファイルに埋め込むこともできます。

さいごに

 vueの作者さんによるとvue-loaderでtsを扱えるようにするのは容易ではないようです1。vue-loaderが対応するまでは、こんな感じでTypeScriptを利用してみてはどうでしょうか。

13
8
0

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
13
8