SystemJSでAngular 2の環境を構築する

SystemJSでAngular 2の環境を構築する

SystemJSwebpackBrowserifyのようなJavaScriptファイルの依存関係を解決するためのモジュール管理ツールです。

Angular 2ではquickstartではSystemJSを利用したコンパイル環境を、Angular CLIではwebpackを利用したコンパイル環境を提供しています。

今回は用意されている環境を利用せずに0ベースでSystemJSの環境を構築していく方法を解説します。
(quickstartの設定内容を最小限にして順序立てて解説しています)

package.jsonの作成

まずはターミナルなどで以下のコマンドを入力してpackage.jsonの作成を行います。

npm init -y

ローカルサーバーの構築

SystemJSではAjaxでファイルの取得などを行うためローカルサーバーの設定が必要になります。

以下のコマンドでlite-serverのインストールを行い、

npm install lite-server --save-dev

設定ファイルのbs-config.jsonを作成します。

{
  "server": {
    "baseDir": "src",
    "routes": {
      "/node_modules": "node_modules"
    }
  }
}

今回はsrcフォルダを内容をローカルに表示し、node_modulesにもアクセスできるようにします。

ひとまず、確認用にsrc/index.htmlを作成します。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <h1>Hello World!</h1>
</body>
</html>

package.jsonのscriptsにはローカルサーバー起動用のserveコマンドを登録しておきます。

  "scripts": {
    "serve": "lite-server -c=bs-config.json"
  },

これで以下のコマンドでローカルサーバーが立ち上がります。

npm run serve

TypeScriptのコンパイル環境の構築

次にTypeScriptのコンパイル環境を構築しましょう。

以下のコマンドでTypescriptのインストールを行い

npm install typescript --save-dev

srcディレクトリの中にTypeScriptの設定ファイルtsconfig.jsonを作成します。

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}

package.jsonのscriptsにはビルド用のコマンドと監視ビルド用のコマンドを登録しておきます。

  "scripts": {
    "serve": "lite-server -c=bs-config.json",
    "build": "tsc -p src/",
    "build:watch": "tsc -p src/ -w"
  },

これで以下のコマンドでTypeScriptのコンパイルが可能になります。

npm run build

試しに./src/main.tsファイルを作成してコマンドを入力してみましょう。

let foo:String = 'ok'
console.log(foo);

コンパイルされた./src/main.jsファイルと./src/main.js.mapファイルが出力されるはずです。

var foo = 'ok';
console.log(foo);
//# sourceMappingURL=app.js.map

.tsファイルを監視しておき変更があれば即座にコンパイルを行うということをしたいのであれば以下のコマンドを実行します。

npm run build:watch

サーバー起動とコンパイル処理を並列で実行

サーバー起動の「npm run serve」とコンパイル処理の「npm run build:watch」を同時に行うようにしましょう。

以下のコマンドでconcurrentlyのインストールを行い、

npm install concurrently --save-dev

package.jsonにstartコマンドを追加します。

  "scripts": {
    "serve": "lite-server -c=bs-config.json",
    "build": "tsc -p src/",
    "build:watch": "tsc -p src/ -w",
    "start": "concurrently \"npm run build:watch\" \"npm run serve\""
  },

これで以下のコマンドでローカルサーバーとコンパイル環境が立ち上がります。

npm start

SystemJSによるファイル読み込み

次にSystemJSによるファイルの読み込みを行います。

まずはsystemjsのインストール。

npm install systemjs --save

次に設定ファイルをsrc/systemjs.config.jsとして作成します。

(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',
    
      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
     
      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);

最後にsrc/index.htmlでこれらのファイルを読み込み実行しましょう。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <h1>Hello World!</h1>
  <script src="node_modules/systemjs/dist/system.src.js"></script>
  <script src="systemjs.config.js"></script>
  <script>
    System.import('main.js').catch(function(err){ console.error(err); });
  </script>
</body>
</html>

これでローカルサイト内でsrc/main.ts内に記述していた内容「cosnole.log('ok')」が出力されます。

Angular 2との連携

それでは最後にAngular 2でブラウザ上にHellow Angularと出力するまで解説します。
(Angularのコードの内容は解説しません)

まずは、必要ファイル(@angularとrxjs、core-js)のインストールを行います。

npm install @angular/{core,common,compiler,platform-browser,platform-browser-dynamic} rxjs zone.js core-js --save

つぎにsrc/index.htmlの内容を修正します。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <my-app>Loading…</my-app>
  <script src="node_modules/core-js/client/shim.min.js"></script>
  <script src="node_modules/zone.js/dist/zone.js"></script>
  <script src="node_modules/systemjs/dist/system.src.js"></script>
  <script src="systemjs.config.js"></script>
  <script>
    System.import('main.js').catch(function(err){ console.error(err); });
  </script>
</body>
</html>

rxjsとcore-jsを読み込み、my-appコンポーネントを配置しています。

次にsrc/main.tsの内容を修正

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  
import { AppModule } from './app/app.module';
  
platformBrowserDynamic().bootstrapModule(AppModule);

次にsrc/app/app.module.tsを作成します。

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
  
import { AppComponent }  from './app.component';
  
@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

最後にsrc/app/app.component.tsを作成します。

import { Component } from '@angular/core';
 
@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>`,
})
export class AppComponent  { name = 'Angular'; }

これでブラウザ上にHellow Angularと出力されます。

Hello Angular

最近ではquickstartやAngular-CLIのような便利なツールがありますが、行われている設定や設定ファイルなどを理解しておくと、なにかあった時に役にたちますので。

作成したものはGitHubにあげてますのでご利用ください。

関連エントリー

anyenv+ndenvでプロジェクトごとにnode.jsのバージョンを切り替える
webpackでJavaScriptライブラリを利用する
npmとBrowserifyでjQueryプラグインを管理する
babelifyで始めるES6
Babelで始めるES6入門

スポンサードリンク

«anyenv+ndenvでプロジェクトごとにnode.jsのバージョンを切り替える | メイン | [書評] Webディレクションの新・標準ルール»