2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Typescript環境構築

Posted at

Typescriptってなんなん

javascriptに型を加えた言語です。
typescriptをトランスパイルするとjavascriptになります。

環境

node.js v8.1.2

パッケージインストール

以下のパッケージをインストール、グローバルを汚染したくないので-gオプションは使用しません。

npm install --save-dev typescript gulp gulp-typescript

gulpタスク作成

gulpfile.jsを以下の様に記載します。

gulpfile.js
'use strict';

const gulp = require('gulp');
const ts = require('gulp-typescript');
const tsProject = ts.createProject('tsconfig.json');

gulp.task('ts-build', () => {
    return tsProject.src()
        .pipe(tsProject())
        .js.pipe(gulp.dest('dist'));
});

スクリプト追加

package.jsonにスクリプト追加する。

package.json
  - 省略 -
  "scripts": {
    "ts-build": "gulp ts-build"
  },
  - 省略 -

Typescriptの設定ファイル作成

tsconfig.jsonを作成し以下の様に記載する。

tsconfig.json
{
    "compilerOptions": {
        "target": "ES2017",
        "sourceMap": true
    },
    "include": [
        "src/**/*.ts"
    ]
}

お試し

srcディレクトリ以下にgreeter.tsを作成し以下を記載する。

greeter.ts
class Student {
    fullName: string;
    constructor(public firstName, public middleInitial, public lastName) {
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
}

interface Person {
    firstName: string;
    lastName: string;
}

function greeter(person : Person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}

var user = new Student("Jane", "M.", "User");

console.log(greeter(user));

以下のコマンドを実行し、typescriptがjavascriptになることを確認する。

npm run ts-build
./dist/greeter.js
class Student {
    constructor(firstName, middleInitial, lastName) {
        this.firstName = firstName;
        this.middleInitial = middleInitial;
        this.lastName = lastName;
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
}
function greeter(person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}
var user = new Student("Jane", "M.", "User");
console.log(greeter(user));

2
6
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
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?