C-MOON

主にプログラミング勉強中のメモを書いていきます。

Angularプロジェクトでjavascriptライブラリを使用する方法

angular-cliで作成したプロジェクトで、自作のjavascriptライブラリを使用する方法です。

環境

  • angular-cli: 6.0.8
  • typescript: 2.7.2

Angularプロジェクトの作成

ngコマンドでテスト用のアプリケーションを作成します。

$ ng new my-app

Javascriptファイルの準備

例として、以下のようなjavascriptファイル「hello.js」をsrc/assrtsに作成します。
※src/assrts以外のディレクトリに配置すると動作しません。
f:id:thenewsinpu:20180615230321p:plain

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

設定ファイルの編集

angular.jsonの”scripts”にhello.jsのファイルパスを追加します。

build”: {
  (省略)
  "options": 
    (省略)
    "scripts": [
      "src/assets/hello.js"
    ]

index.htmlの編集

index.htmlでhello.jsを呼び出します。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyApp</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <!--  hello.js呼び出し追加 -->
  <script src="assets/hello.js"></script>

</head>
<body>
  <app-root></app-root>
</body>
</html>

ライブラリの呼び出し

app.component.tsに以下①、②を追加します。
Javascriptの関数をTypescriptで呼び出すための型定義を行い、②Hello関数を呼び出します。

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

// ① 型定義
declare function Hello(): void;
// 型定義はこれ↓でも良い
// declare var Hello: any;

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

  // ② hello.jsのHello()を呼び出し
  constructor() {
    Hello();
  }
}

実行結果

コンソールに「Hello !」と表示されれば成功です。 f:id:thenewsinpu:20180615233459p:plain

参考文献:

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

javascript - using external JS libraries in my angular 2 project - Stack Overflow