【问题标题】:include an external Javascript library into an Angular Project Globally & Properly将外部 Javascript 库包含在全局和正确的 Angular 项目中
【发布时间】:2025-12-22 14:40:09
【问题描述】:

在使用 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 angular ionic-framework angular5


    【解决方案1】:

    要达到预期结果,请使用以下选项,将 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";

    @组件({ 选择器:'我的应用', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) 导出类 AppComponent { 名称 = '角'; 现在 = 新日期(); 结果:任何=''; 测试:任何=日期格式;

    构造函数(){ 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 中轻松获得用于格式化日期,因此只需从 @angular/common 导入(在上面的示例中添加示例工作代码)

    【讨论】:

      【解决方案2】:

      这取决于每个库如何做到这一点。您可以尝试查看是否有 angular 的包装器库。对于全局库,您可以将其添加到 index.htmlangular.json 的脚本数组中。

      您也可以像以前一样使用import,如果库允许,这是最干净的方式。据我所知,dateformat 库还可以,您只需要更正一个错字:(dateformat vs dateFormat)

      import * as dateFormat from "dateformat";
      
      dateFormat(new Date(), "dddd, mmmm dS, yyyy, h:MM:ss TT")
      

      【讨论】:

        【解决方案3】:

        包含外部纯 JavaScript 库的最佳方法是使用 npm install ... 安装它,然后将所有 .js 和 .css 文件(来自 node_modules 文件夹)分别添加到 angular.json 文件中的 @ 987654324@ 和 styles 属性。 这些脚本和样式将与您的应用程序捆绑在一起,并且在每个组件中您都可以访问它们定义的全局变量。

        例如你可以 npm 安装 jQuery,将它添加到 angular.json 文件的 script 属性中,如下所示:

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

        像这样在顶部声明它:

        import * as $ from 'jquery';
        

        然后就可以正常使用了

        EXAMPLE

        【讨论】: