jQueryを使用する - declare使用例

本来外部モジュールはnpm install hogehogeでインストールを行えばComponentで使用できるようになるが、CDNやインストールしないタイプのモジュールでは使用できない。

インストール

Jquery本体と型のインストールを行う。

npm install jquery --save
npm install @types/jquery --save-dev
1
2

angular.jsonの編集

scriptタグ(2箇所)にjquery.jsを読み込む設定を記述する。

            "scripts": [
              "node_modules/jquery/dist/jquery.js"
            ]
1
2
3

sample

画像animationサンプル。

HTMLに関してはjQueryの書き方がそのまま使える。

<!-- app.component.ts -->
<button (click)="debug()">click me</button>
<svg
  xmlns="http://www.w3.org/2000/svg"
  enable-background="new 0 0 24 24"
  height="24"
  viewBox="0 0 24 24"
  width="24"
  id="book"
>
  <g><rect fill="none" height="24" width="24" /></g>
  <g>
    <g>
      <g>
        <path
          d="M8.5,14.5L4,19l1.5,1.5L9,17h2L8.5,14.5z M15,1c-1.1,0-2,0.9-2,2s0.9,2,2,2s2-0.9,2-2S16.1,1,15,1z M21,21.01L18,24 l-2.99-3.01V19.5l-7.1-7.09C7.6,12.46,7.3,12.48,7,12.48v-2.16c1.66,0.03,3.61-0.87,4.67-2.04l1.4-1.55 C13.42,6.34,14.06,6,14.72,6h0.03C15.99,6.01,17,7.02,17,8.26v5.75c0,0.84-0.35,1.61-0.92,2.16l-3.58-3.58v-2.27 c-0.63,0.52-1.43,1.02-2.29,1.39L16.5,18H18L21,21.01z"
        />
      </g>
    </g>
  </g>
</svg>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

component.tsでは

  • import * as jQuery from 'jquery';は型呼び出しのため
  • declare var $: typeof jQuery;$に型を定義する。
// app.component.ts
import { Component } from '@angular/core';
import * as jQuery from 'jquery';  // jqueryの読み込み
declare var $: typeof jQuery;  // $の型を宣言する
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  title = 'jquery-test';
  constructor() {}
  debug(): void {
    $('#book').animate(  // jQeuryが型を見ながらコーディングできる。
      {
        opacity: 0.25,
        right: '+=50',
        height: 'toggle',
      },
      5000
    );
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

declareはアンビエント宣言と呼ぶみたい。componentソース上にはない変数(関数、Objectなどを含む)を定義済みとする機能。angular.jsonにjquery.jsが読み込まれているためグローバル変数として$関数は存在しているが、app.component.tsには$が存在しないためdeclare宣言が存在しない場合、コンパイルエラーになる。$はコードに見えないけど存在していますよ!みたいな感じで使える。

ここの例はjQueryを使用しているがCDNなどによりindex.htmlの<script>により宣言したjsにも使える。