我尝试使用它与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和MomentJS作为库,这为我解决了这个问题

/*
 * Import Custom Components
 */
import * as moment from 'moment/moment'; // please use path to moment.js file, extension is set in system.config

// under systemjs, moment is actually exported as the default export, so we account for that
const momentConstructor: (value?: any) => moment.Moment = (<any>moment).default || moment;

在那里工作对我来说很好。

其他回答

对于angar2和systemjs和JSPM必须做:

import * as moment_ from 'moment';
export const moment =  moment_["default"];

var a = moment.now();
var b = moment().format('dddd');
var c = moment().startOf('day').fromNow();

要在Typescript项目中使用它,你需要安装moment:

NPM安装时刻——保存

在安装moment之后,你可以在导入后的任何.ts文件中使用它:

Import * as moment from "moment";

我自己在Angular中使用Moment的版本

NPM I瞬间——保存

import * as _moment from 'moment';

...

moment: _moment.Moment = _moment();

constructor() { }

ngOnInit() {

    const unix = this.moment.format('X');
    console.log(unix);    

}

首先导入moment作为_moment,然后声明类型为_moment的moment变量。初始值为_moment()的Moment。

简单地导入moment不会给你任何自动补全,但如果你将声明type moment interface from _moment namespace from 'moment' package initialized with moment namespace invoked _moment()会给你自动补全moment的api。

我认为这是使用moment而不使用@types类型或angular提供程序的最具角度的方式,如果你正在寻找像moment这样的普通javascript库的自动完成。

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

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

我们现在使用模块,

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

在NPM安装angar2 -moment后

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