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


当前回答

除了SnareChop的答案,我还必须更改momentjs的类型文件。

在moment-node.d。我替换的ts:

export = moment;

with

export default moment;

其他回答

除了SnareChop的答案,我还必须更改momentjs的类型文件。

在moment-node.d。我替换的ts:

export = moment;

with

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

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

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

NPM安装时刻——保存

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

Import * as moment from "moment";

尝试在tsconfig.json中添加" allowsyntheticdefaulultimports ": true。

国旗的作用是什么?

这基本上是告诉TypeScript编译器,可以使用ES6导入语句,即。

import * as moment from 'moment/moment';

在CommonJS模块上,比如Moment.js,它没有声明默认导出。该标志只影响类型检查,不影响生成的代码。

如果你使用SystemJS作为模块加载器,这是必要的。如果你告诉TS编译器你使用SystemJS,该标志将自动打开:

"module": "system"

如果ide被配置为使用tsconfig.json,这也将删除由它们抛出的任何错误。

对于angar2 RC5,这为我工作…

第一次安装时刻通过NPM

npm install moment --save

然后在你想要使用它的组件中导入moment

import * as moment from 'moment';

最后,在systemjs.config.js中配置"map"和"packages"

// map tells the System loader where to look for things
  var map = {
  ....
  'moment':                     'node_modules/moment'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    ...
    'moment':                       { main:'moment', defaultExtension: 'js'}
  };