我尝试使用它与typescript绑定:

npm install moment --save
typings install moment --ambient -- save

test.ts:

import {moment} from 'moment/moment';

如果没有:

npm install moment --save

test.ts:

var moment = require('moment/moment');

但是当我调用moment.format()时,我得到一个错误。 应该是简单的,谁能提供一个命令行/导入组合,将工作?


当前回答

——2017年11月1日更新

Typings现在已弃用,被npm @types所取代。从现在开始,除了npm,获取类型声明将不需要任何工具。要使用Moment,您不需要通过@types安装类型定义,因为Moment已经提供了自己的类型定义。

因此,它简化为3个步骤:

1 -安装时刻,包括类型定义:

npm install moment --save

2 -在HTML文件中添加script标签:

<script src="node_modules/moment/moment.js" />

3 -现在你可以使用它了。时期。

today: string = moment().format('D MMM YYYY');

——原创答案

这只需要3个步骤:

1 -安装力矩定义- *.d。ts文件:

typings install --save --global dt~moment dt~moment-node

2 -在HTML文件中添加script标签:

<script src="node_modules/moment/moment.js" />

3 -现在你可以使用它了。时期。

today: string = moment().format('D MMM YYYY');

其他回答

下面的方法对我很有效。

首先,安装moment的类型定义。

类型安装时刻—保存

(注:NOT -ambient)

然后,为了解决缺乏适当的导出:

import * as moment from 'moment';

如果你愿意添加更多的第三方包,我使用了angular2-moment库。安装非常简单,您应该遵循README上的最新说明。因此,我还安装了类型。

它对我来说就像一个魅力,几乎没有添加任何代码来让它工作。

Moment.js现在在v2.14.1支持TypeScript。

参见:https://github.com/moment/moment/pull/3280

angular2-moment库有像{{myDate | amTimeAgo}}这样的管道用于.html文件中。

这些管道也可以作为组件类(.ts)文件中的Typescript函数来访问。首先按照提示安装库:

npm install --save angular2-moment

在node_modules/angular2-moment现在将是“.pipe.d”。例如calendar.pipe.d。ts, date-format.pipe.d。t等等。

每一个都包含等效管道的Typescript函数名,例如,DateFormatPipe()是amDateFormatPipe的函数。

要在项目中使用DateFormatPipe,请在app.module.ts中将其导入并添加到全局提供程序中:

import { DateFormatPipe } from "angular2-moment";
.....
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, ...., DateFormatPipe]

然后在任何你想要使用该函数的组件中,将它导入到顶部,注入到构造函数中并使用:

import { DateFormatPipe } from "angular2-moment";
....
constructor(.......,  public dfp: DateFormatPipe) {
    let raw = new Date(2015, 1, 12);
    this.formattedDate = dfp.transform(raw, 'D MMM YYYY');
}

要使用任何函数都遵循这个过程。如果有一种方法可以访问所有的函数,那就太好了,但上面的解决方案都不适合我。

使用ng命令行

> npm install moment --save

在app.module

import * as moment from 'moment';

providers: [{ provide: 'moment', useValue: moment }]

在组件

constructor(@Inject('moment') private moment)

这样你就导入了一次时刻

5 . UPDATE Angular =>

{
   provide: 'moment', useFactory: (): any => moment
}

对我来说,在aot中工作 还有通用的

除了利用时间,我什么都不喜欢。时刻 我得到了

Error   Typescript  Type 'typeof moment' is not assignable to type 'Moment'. Property 'format' is missing in type 'typeof moment'.