LoginSignup
11
11

More than 5 years have passed since last update.

gulp+webpackの環境でAngular2のHelloWorld

Posted at

Angular2を使いたくて、とりあえず公式の5 Min Quickstartを見たら、SystemJSを使っていました。
SystemJSはよく知らないんですが、普段はwebpackを使っているのでそちらで動かしたい。
どうせならgulpで一発コンパイルしたいということで、gulp+webpack環境でAnuglar2を動かすやり方について書いていきたいと思います。
ちなみに、Angular2のバージョンはrc4です。
正式リリースまだかなー。

必要なもの

  • npm
  • webpack
    • ts-loader
  • gulp
    • gulp-webpack

Angular2のインストール

以下のコマンドを実行し、npmでAngular2をインストールします。
今回使うのは@angular/platform-browser-dynamicと@angular/coreですが、一応Angular2関連のものはすべてインストールしておきます。

npm i -S @angular/common @angular/compiler @angular/core @angular/forms @angular/http @angular/platform-browser @angular/platform-browser-dynamic @angular/router @angular/router-deprecated @angular/upgrade rxjs@5.0.0-beta.6 zone.js@0.6.12 core-js

ファイルの作成

Angular2を読み込んで実行するためのHTMLファイル(index.html)とエントリーポイントとなるtsファイル(myapp.ts)を作成する。

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Hello Angular 2!</title>
</head>
<body>
 <!-- ここにMyAppComponentを挿入する -->
  <my-app>Loading…</my-app>
</body>
<!-- webpackで結合後のjsファイルの読み込み-->
<script src="./bundle.js"></script>
</html>
myapp.ts
import "core-js";
import "rxjs/Rx";
import "zone.js/dist/zone";

import {bootstrap} from "@angular/platform-browser-dynamic";
import {Component} from "@angular/core";
// myAppコンポーネント定義
@Component({
  selector: "my-app",
  template: `
    <h1>Hello World!</h1>
  `
})
class MyAppComponent {
}
//index.htmlで使うための準備
bootstrap(MyAppComponent);

webpackの設定

webpack.config.jsを以下のように設定します。

webpack.config.js
module.exports = {
    // エントリーポイント
    entry:'./app.ts',
    // 出力するファイル名
    output: {
        filename: './bundle.js'
    },
    // 依存関係
    resolve: {
        root:['./node_modules'],
        extensions:['', '.webpack.js', 'web.js', '.js', '.ts']
    },
    // TypeScriptを読み込むためのloader
    module: {
        loaders: [
            { test: /\.ts$/, loader: 'ts-loader' }
        ]
    }
}

gulpの設定

gulp.jsを以下のように記述します。
基本的な設定はwebpackの方でやっているので、こっちの設定はあまり中身があるものではなく、ほぼ呼び出しだけです。

gulp.js
var gulp = require('gulp');

var webpack = require('gulp-webpack');
var webpackConfig = require('./webpack.config.js');

// TypeScriptのコンパイルとwebpackの実行
gulp.task('ts', function () {
    // TypeScriptのコンパイル
    var tsResult = gulp.src(['./*.ts'])
        .pipe(webpack(webpackConfig))
        .pipe(gulp.dest('./'));
});

// コマンドで「> gulp」と入力したときのタスク
gulp.task('default', ['ts']);

コンパイル

ここまでできたら、gulpコマンドを実行することでbandle.jsが生成されます。
Angular2の依存関係も解決しているので、index.htmlでは<script src="./bundle.js"></script>だけで作成したComponentを使うことができます。

11
11
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
11
11