クロコめも2。

ただのめもー

TypeScriptでVue.jsを使うサンプル(前半)

【計画】前半と後半に分ける

前半

プロジェクトの作成と簡単なアプリ作成

後半

vue-router組み込み

主要な使用技術

  • TypeScript 1.6.2
  • vue 1.0.8
  • vue-router 0.7.5
  • vue-class-component 2.0.0
  • TypescriptのコンパイルオプションはES6

大まかな手順

  1. プロジェクト作成と環境の準備
  2. TypeScriptまわりの準備
  3. vueの簡単なサンプル作り
  4. vue-router挑戦

プロジェクト作成と環境の準備

# ディレクトリ作成
mkdir プロジェクトのフォルダ
cd プロジェクトのフォルダ
mkdir build
mkdir -p  src/{components,views,assets,directives,filters}
mkdir src/assets/js

# npm で必要なものをあつめてくる
npm init 
npm i -g webpack webpack-dev-server mocha typescript tsd tslint
npm i -S vue vue-class-component vue-router
npm i -D babel-loader@^5.3 webpack style-loader css-loader sass-loader ts-loader html-loader typescript tsd tslint-loader mocha mocha-loader chai

# tsd で必要なものを集めてくる
tsd init
tsd install vue --save
tsd install require --save

# tslint用の定義ファイルをテンプレートからコピってくる。しかしこれ厳しすぎてつらいので適宜ゆるく改修する必要あり
cp ./node_modules/tslint-loader/node_modules/tslint/docs/sample.tslint.json ./tslint.json

webpack.config.jsの作成

module.exports = {
    entry: {
        app: "./src/assets/js/entry.ts"
    },
    output: {
        path: './build/js',
        publicPath: '/js/',
        filename: "[name].js"
    },
    resolve: {
        alias: {
            vue: "vue/dist/vue"
        },
        modulesDirectories: ['node_modules', 'src/', 'src/assets/js/', 'src/views/', 'src/components/'],
        // require()するときに拡張子を省略可能にします
        extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
    },
    devServer: {
        contentBase: "./build",
    },
    module: {
        preloaders: [
            {
                test: /\.ts$/,
                loader: "tslint"
            }
        ],
        loaders: [
            {
                test: /\.scss$/,
                loader: "style!css!sass"
            },
            {
                test: /\.html$/,
                loader: "html"
            },
            {
                test: /\.ts(x?)$/,
                loader: 'babel-loader?sourceMaps=true!ts-loader'
            }
        ]
    }
};

tsconfig.jsonを作成する

{
  "compilerOptions": {
    "module": "commonjs",
    "removeComments": true,
    "noImplicitAny": false,
    "target": "es6",
    "sourceMap": true,
    "experimentalDecorators": true,
    "preserveConstEnums": true
  },
  "exclude": [
    "node_modules",
    "build"
  ]
}

src/assets/js/にentry.tsを作成

console.log("hello");

/build/index.htmlを作成

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>sample</title>
</head>
<body>
    <div id="app">this is app</div>
    <script type="text/javascript" src="js/app.js" charset="utf-8"></script>
</body>
</html>

ここで一旦、webpack-dev-serverを起動してプレビュー

起動コマンド : webpack-dev-server -d --inline
http://localhost:8080

コンソールにhelloと表示されたらここまでOK

横道:IntelliJ使ってる場合の設定

Preferences->Languages & Frameworks->JavaScript

Preferences->Languages & Frameworks->TypeScript

  • Enable TypeScript Compilerをチェックする(重かったらチェック外してもいいかも)
  • コマンドラインオプション --noImplicitAny --target ES6 --experimentalDecorators
  • generate sourceMapのチェックをはずす。

Preferences->Languages & Frameworks->TypeScript->Tslint

  • プロジェクトのtslint.jsonを設定する

横道から復帰

TypeScriptまわりの準備

typingsの中にあるvue.d.tsの中でexport =とある部分をexport defaultと書き換える
※es6を使うときに怒られちゃうからこれでごまかす。。。

独自定義ファイルディレクトリを作る

mkdir -p custom-typings/vue-class-component

custom-typings/vue-class-component/vue-class-component.d.tsを作る(これでいいのか不明)

declare module "vue-class-component" {
    let VueComponent:ClassDecorator;
    export default VueComponent;
}

custom-typings/custom.d.tsを作る

/// <reference path="vue-class-component/vue-class-component.d.ts" />

vueの簡単なサンプル作り

src/assets/js/entry.tsを書き換え

/// <reference path="../../../typings/tsd.d.ts" />
import Vue from "vue";
require("../sass/main.scss");
new Vue(require("../../views/app"));

src/assets/sass/main.scss作成(てきとー)

body {
  margin: 0px;
  padding: 0px;
}
.main-header {
  margin: 0px;
  padding: 3px;
  background-color: #fafafa;
  border-bottom: 1px solid #CCCCCC;
  text-align: center;
}

.main-footer {
  position: fixed;
  width: 100%;
  margin: 0px;
  padding: 3px;
  background-color: #fafafa;
  border-top: 1px solid #CCCCCC;
  bottom: 0px;
}

src/views/app/index.tsを作成

/// <reference path="../../../typings/tsd.d.ts" />
import Vue from "vue";
import Header from "../../components/header/index";
const app = new Vue({
    el: "#app",
    template: require('./template.html'),
    components: {
        'app-header': Header
    }
});

src/views/app/template.htmlを作成

<app-header></app-header>

src/components/header/index.tsを作成

/// <reference path="../../../typings/tsd.d.ts" />
/// <reference path="../../../custom-typings/custom.d.ts" />
import VueComponent from "vue-class-component";

@VueComponent
export default class Header {
    public static template:string = require("./template.html");

    public ready():void {
        console.log("hogehoge");
    }
}

src/component/header/template.html

<div class="main-header">
    <h3>TypeScript & Vue.js sample</h3>
</div>

サーバを起動して動作確認する。ヘッダーが表示されていればここまでOK

横道2 ChromeのVue Devtoolsについて

能力の無さは積極的にツールでカバーしたい。ということで便利ツールChromeプラグイン「Vue Devtools」
webpackの起動オプションに--inlineを設定してあったり、babel-loaderかますときにsourceMapつけてるのはこのツールを使えるようにするためです。
このプラグインのおかげで表示されているコンポーネントの情報をブラウザで実行時に見ることができます。
chrome上でブレイクポイント置いてステップ実行できるようになるものも相当嬉しい(それはVue Devtoolsの機能じゃないけど)