簡體   English   中英

在全球范圍內正確地將外部Javascript庫包含到Angular項目中

[英]include an external Javascript library into an Angular Project Globally & Properly

在Angular中進行開發時,我們經常需要使用外部JS庫,因此,我今天要尋求在全球范圍內實現此目的的最簡潔方法。

實際上我正在嘗試包括dateFormat JS庫: https ://www.npmjs.com/package/dateformat

問題1:JS庫是使用相同的體系結構創建的,還是不只一種方法將其包含在項目中。

問題2:如何將這個特定的庫全局地包含在我的項目中,我可以在app.module.ts中做些什么使其在所有項目中可用嗎?

我實際上所做的是:

npm install dateformat

我試圖將其簡單地添加到一個組件中,但是使用此方法失敗:

import * as dateformat from "dateformat";

@Component({
  selector: 'page-notifications',
  templateUrl: 'notifications.html'
})

export class NotificationsPage {

    constructor(){
        console.log("test",dateFormat(new Date(), "dddd, mmmm dS, yyyy, h:MM:ss TT") );
    }

}

包括外部,普通的JavaScript的最好方法,圖書館使用安裝npm install ...然后添加所有的.js和.css文件(從node_modules文件夾)在angular.json文件中分別scriptsstyles屬性。 這些腳本和樣式將與您的應用程序捆綁在一起,並且在每個組件中您都可以訪問它們定義的全局變量。

例如,您可以npm安裝jQuery,將其添加到script屬性中的angular.json文件中,如下所示:

"scripts": ["../node_modules/jquery/dist/jquery.min.js"]

像這樣在頂部聲明:

import * as $ from 'jquery';

然后您可以像平常一樣使用它

這取決於每個庫的操作方式。 您可以嘗試查看是否有用於角度的包裝器庫。 對於全局庫,您可以將其添加到index.htmlangular.json的scripts數組中。

您也可以像使用import一樣使用import ,如果庫允許的話,這是最干凈的方法。 據我所知, dateformat庫是可以的,您只需要糾正一個錯字即可:(dateformat vs dateFormat)

import * as dateFormat from "dateformat";

dateFormat(new Date(), "dddd, mmmm dS, yyyy, h:MM:ss TT")

為了獲得預期的結果,請使用以下使用npm install @ types / dateformat和dateformat的選項

問題: TypeScript 2.0中的類型聲明無需任何工具,僅在npm即可。 @types范圍包包含外部庫的類型定義(例如lodash,jQuery,dateformat),這些節點的類型定義使我們可以使用require作為dateformat庫的全局函數

請參考此鏈接以獲取更多詳細信息http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html https://basarat.gitbooks.io/typescript/docs/types/@types.html

參考代碼:

npm install @types/dateformat --save
npm install dateformat --save

component.ts

import { Component } from '@angular/core'; import {formatDate } from '@angular/common'; import * as dateformat from "dateformat";

@Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { name = 'Angular'; now = new Date(); result: any = ''; test:any = dateformat;

constructor(){ console.log("test",formatDate(this.now, 'dd-MM-yyyy hh:mm:ss a', 'en-US', '+0530')); this.result = this.test.default(new Date(), "dddd, mmmm dS, yyyy, h:MM:ss TT") console.log("dateformat", this.result); } }

工作代碼示例-https: //stackblitz.com/edit/angular-wmxejs?file=src/app/app.component.ts

注意:包含的formatDate是內置的,可以用角度來方便地格式化日期,因此只需從@ angular / common導入(在上面的示例中添加了示例工作代碼)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM