LoginSignup
18
16

More than 5 years have passed since last update.

angular-cliプロジェクトにJavaScriptライブラリを組み込む方法

Posted at

環境

このドキュメントでは次のバージョンのangular-cliで生成したプロジェクトについて記述しています。

公式情報

Angular2用のサードパーティライブラリであれば、npm installで取得可能になっていたり、ライブラリのREADME等に説明があるため困ることはないでしょう。

また、有名どころのライブラリであればTypeScriptの型定義ファイルが@typesに集約されているためこちらもnpm installしてimportして利用することができます。

その他のJSライブラリの組み込み方法

npmに登録されていないし誰もTypeScriptの型定義の面倒を見てくれていない、何かの案件用のライブラリや昔からあるオレオレライブラリへの対応方法についてまとめます。

このドキュメントではそのようなライブラリの例として、hello.jsがあるとします。
単純に関数1つにしておきます。

function Hello() {
  console.log('hello !');
}

ファイルの配置

プロジェクト内のどこかに置きます。
このドキュメントでは Project/src/js/hello.js に置いてみます。

公式のGlobal Library Installationの通り、angular-cli.json に記述を追加します。

"scripts": [
  "../src/js/hello.js"
],

scriptsに記述を追加することで ng buildng serve した時にAngularアプリにhello.jsが含まれるようになります。

ライブラリの呼び出し

hello.jsのHello関数を呼び出してみます。

import { Component } from '@angular/core';

// 型定義は手抜き
declare var Hello: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';

  constructor() {
    Hello(); // <- 呼び出せる
  }
}

ng test対応

ng buildng serve では問題ないのですが、ng test では次のようなReferenceErrorが発生してしまいます。

Failed: Error in :0:0 caused by: Hello is not defined
ReferenceError: Hello is not defined

ng test のテスト中でもライブラリを利用するには karma.conf.js にも記述を追加する必要があるようです。

files: [
  // test.tsよりも先に記述すること!!
  { pattern: './src/js/hello.js', included: true, watched: false },
  { pattern: './src/test.ts', watched: false }
],

※注意
test.tsの次に追加してしまうと相変わらずReferenceErrorが発生してしまいます。test.tsの前に記述を追加しましょう。

18
16
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
18
16