LoginSignup
0
1

More than 5 years have passed since last update.

TypeScript2.xをwebpack2.xでビルドする最弱サンプル

Posted at

概要

複数のファイルで構成したTypeScript(2.x系)をwebpack(2.x系)でJavaScript(ES5)にまとめます。
作成されたJavaScriptをコマンド実行してHello的なもの表示するだけの最弱サンプルです。

TypeScript(2.x系)をwebpack(2.x系)でまとめるだけのヤツをやりたいけど、あまりに低レベルなため見当たらなかったので、自分メモとして記録します。

開発環境

Windows10
node.js : v6.10.1

構成

[プロジェクトルートフォルダ]
.
├── package.json
├── src
│ ├── Index.ts
│ └── Test.ts
├── tsconfig.json
└── webpack.config.js

ソースコード

package.json
{
  "name": "typescript2_webpack2_sample",
  "version": "1.0.0",
  "license": "MIT",
  "scripts": {
    "build": "webpack --config webpack.config.js"
  },
  "devDependencies": {
    "ts-loader": "^2.0.3",
    "typescript": "^2.2.2",
    "typings": "^2.1.0",
    "webpack": "^2.3.2"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "outDir": "./dist/",
    "module": "CommonJS",
    "target": "es5"
  },
  "files": [
    "./src/Index.ts"
  ]
}

module
上記では"CommonJS"としていますが、正直、私はよくわかってません。
なんとなく"ES6"または"ES2015"としたいんですが、公式サイトのmoduleについての説明で

"ES6" and "ES2015" values may not be used when targeting "ES5" or lower.

とあり、最終的にブラウザで利用できるJavaScript(ES5)にしたかったので、とりあえず"CommonJS"にしました。

webpack.config.js
module.exports = {
    entry: "./src/Index.ts",
    output: {
        filename: "./dist/bundle.js"
    },
    resolve: {
        extensions: [".ts"]
    },
    module: {
        rules: [
            {
                test: /\.ts?$/,
                exclude: /node_modules/,
                use: "ts-loader"
            }
        ]
    }
};
src\Index.ts
import Test from './Test';

let myTest = new Test("Kaban-chan");
myTest.greet();
src\Test.ts
export default class Test {
    private name: string;
    constructor(name: string) {
        this.name = name;
    }
    public greet(): void {
        console.log(`Hello, ${this.name}!!!`);
    }
}

依存パッケージインストール(ダウンロード)

下記コマンド実行。

cd [プロジェクトルートフォルダ]
npm install

ビルド

下記コマンド実行。

cd [プロジェクトルートフォルダ]
npm run build

[プロジェクトルートフォルダ]\dist\bundle.jsに変換・まとめられたJSファイルができます。

実行

下記コマンド実行。

cd [プロジェクトルートフォルダ]
node dist\bundle.js
Hello, Kaban-chan!!!

↑のように「Hello, Kaban-chan!!!」が表示されます。

完了

以上です。

0
1
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
0
1