添加时刻到 angular 2 (angular cli)

Add moment to angular 2 (angular cli)

我已经按照 cli github page 中的指导行进行操作。但是我无法让它在我的应用程序中运行。
这是我所做的:

  1. 安装时刻:npm install moment --save
  2. 安装时刻 ts 类型:npm install @types/moment --save
  3. 在我的组件之一中导入时刻:import * as moment from 'moment';

我收到以下错误:

有什么想法吗?

在最新版本的angular-cli中安装第三方库变得更简单了。 (webpack 版本,不是 systemjs 版本)。

转到项目根目录下的 angular-cli.json 并进行配置,

{
  ...
  "apps": [
     ...
     "scripts": [
        "../node_modules/moment/min/moment.min.js"
     ]
     ...
  ]
  ...
}

最后,在您的 any.component.ts 中,您可以像这样导入它,

import { Component, OnInit } from '@angular/core';
import * as moment from 'moment';

@Component({
    selector: '[id=home]',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
    constructor() { }

    ngOnInit () {
        console.log('today is', moment());
    }
}

您只需要包含使用 CommonJS 语法的时刻,而不是导入。请尝试以下操作:

let moment = require('moment');

这是因为 moment 还不是 ES6 模块,因此不能使用较新的 import 语法。

更新:

仔细想想,我只在单元测试中使用过这种方法。在您的应用程序中使用它可能不会以同样的方式工作,因为这种方法使用节点的 require,它不能在客户端使用。

但是,在您的组件中使用 Moment 时,您可以使用 angular2-moment。可以在 GitHub 页面上找到完整的设置说明,但用法如下所示:

<div>today is {{ Date.now() | amDateFormat:'LL' }}</div>

您还可以使用其他一些管道,它们都记录在 GitHub 页面上。

更新 2:

从 v2.10.0 开始,Moment 现在支持 ES6 语法,因此您应该能够使用任何 ES6 import 语法而不是 require.

我必须更新我的 cli 版本: npm uninstall -g angular-cli @angular/cli npm cache clear npm install -g @angular/cli@latest

这个线程有点旧,但这是我需要的。 Moment 现在带有一个类型定义文件,@types/moment 现在已弃用,取而代之的是这个新文件。为了让 moment 与其他扩展类型定义的库一起工作,例如 fullcallendar,您还需要覆盖 tsconfig.app.json 中的默认模块分辨率

"compilerOptions": {
    ...
    "paths": {
        "moment": [
          "../node_modules/moment/moment.d.ts", 
          "../node_modules/moment/min/moment.min.js"
        ]
    },
},

您还需要更新 angular.json 构建部分以包含时刻:

 "build": {
      ...,
      "options": {
        ...
        "scripts": [ "node_modules/moment/min/moment.min.js"]
 },