新增沒有 typing 的第三方庫

請注意,這僅適用於高達 1.0.0-beta.10 版本的 angular-cli!

某些庫或外掛可能沒有 typing。如果沒有這些,TypeScript 就無法對它們進行型別檢查,從而導致編譯錯誤。仍然可以使用這些庫,但與匯入的模組不同。

  1. 在頁面上包含對庫的指令碼引用(index.html

    <script src="//cdn.somewhe.re/lib.min.js" type="text/javascript"></script>
    <script src="/local/path/to/lib.min.js" type="text/javascript"></script>
    
    • 這些指令碼應新增全域性(例如 THREEmapbox$ 等)或附加到全域性
  2. 在需要這些的元件中,使用 declare 初始化與 lib 使用的全域性名稱匹配的變數。這讓 TypeScript 知道它已經被初始化了。 1

    declare var <globalname>: any;
    

    有些 lib 附加到 window,需要擴充套件才能在應用程式中訪問。

    interface WindowIntercom extends Window { Intercom: any; }
    declare var window: WindowIntercom;
    
  3. 根據需要在元件中使用 lib。

    @Component { ... }
    export class AppComponent implements AfterViewInit {
        ...
        ngAfterViewInit() {
            var geometry = new THREE.BoxGeometry( 1, 1, 1 );
            window.Intercom('boot', { ... }
        }
    }
    
    • 注意:某些庫可能與 DOM 互動,應該在適當的元件生命週期方法中使用。