我尝试使用它与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()时,我得到一个错误。 应该是简单的,谁能提供一个命令行/导入组合,将工作?


当前回答

在systemjs中,我所做的是。我添加了map

map: {
   .....,
   'moment': 'node_modules/moment/moment.js',
   .....
}

然后你可以很容易地导入力矩

import * as moment from 'moment'

其他回答

下面的方法对我很有效:

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

类型存储库中不存在moment-node。您需要重定向到Definitely Typed,以便使用前缀dt使其工作。

我遵循了允许allowSyntheticDefaultImports的建议(因为没有从时刻到我使用的导出),使用System。然后我听从别人的建议使用:

import moment from 'moment';

在system.js配置中映射时刻。由于某些原因,其他import语句对我不起作用

我们现在使用模块,

try import {MomentModule} from 'angular -moment/moment.module';

在NPM安装angar2 -moment后

http://ngmodules.org/modules/angular2-moment

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');
}

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

2017年4月更新:

从版本2.13.0开始,Moment包含了一个typescript定义文件。https://momentjs.com/docs/#/use-it/typescript/

只要用npm在你的控制台类型中安装它

npm install --save moment

然后在你的Angular应用中,导入就像这样简单:

import * as moment from 'moment';

就是这样,你得到了完全的Typescript支持!

额外编辑:要在Typescript中输入一个变量或属性Moment,你可以这样做,例如:

let myMoment: moment.Moment = moment("someDate");