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


当前回答

使用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'.

其他回答

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

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

不确定这对人们来说是否仍然是一个问题,然而……使用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;

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

对于Angular 7+(也支持8,9,10,11):

1:通过命令npm Install moment——save安装moment

2:不要在app.module.ts中添加任何东西

3:只需要在你的组件或任何其他文件的顶部添加import语句,就像这样:import * as moment from 'moment';

4:现在你可以在代码的任何地方使用moment。就像:

myDate = moment(someDate)。格式(“MM / DD / YYYY HH: MM”);

下面的方法对我很有效。

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

类型安装时刻—保存

(注:NOT -ambient)

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

import * as moment from 'moment';

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

NPM安装时刻——保存

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

Import * as moment from "moment";