Aurelia CLI&TypeScript&MomentJS

Mik*_*nen 3 momentjs typescript aurelia aurelia-cli

我没有让Aurelia(CLI)和TypeScript与MomentJS一起工作.我见过Aurelia和Moment问题的解决方案,但他们没有使用Aurelia CLI.

这就是我现在正在做的事情:

使用Aurelia CLI的新Aurelia项目:

au new 
Run Code Online (Sandbox Code Playgroud)

我选择TypeScript而不是Babel.

安装时刻

npm install moment --save
Run Code Online (Sandbox Code Playgroud)

这将安装Moment 2.4.1.我可以从node_modules找到它(包括moment.d.ts).

编辑aurelia.json

我将"时刻"添加到"依赖":

时刻aurelia.json

在app.ts中使用Moment

我现在尝试在app.ts中导入Moment时出现问题.

import { moment } from 'moment';
Run Code Online (Sandbox Code Playgroud)

这给出了错误:"模块"o:/ dev/spikes/amoment/node_modules/moment/moment"没有导出成员'时刻'

更改外壳可修复此错误:

import { Moment } from 'moment';
Run Code Online (Sandbox Code Playgroud)

但在这一点上,我完全陷入困境.当试图使用时刻(或时刻)时,我总是会收到错误"找不到名字'时刻'.这是当前app.ts给出的"找不到名字'时刻'" - 错误:

import { Moment } from 'moment';

export class App {
  message = 'Hello World!';

  hello() : string {
    return moment.format();
  }
}
Run Code Online (Sandbox Code Playgroud)

导入似乎是问题所在.任何想法如何解决这个问题?

更新

修复app.ts看起来如下所示,现在编译的东西.但它在运行时给出了"TypeError:无法读取未定义的属性'格式".

import { Moment } from 'moment';
import { autoinject } from "aurelia-framework";

export class App {
  message: string;
  moment: Moment;

  constructor(moment: Moment) {
    this.moment = moment;
    this.message = this.moment.format('MMMM Do YYYY, h:mm:ss a')
  }
}
Run Code Online (Sandbox Code Playgroud)

更新

基于上一个错误,似乎autoinject在没有@autoinject的情况下无法运行.所以添加了并且错误发生了变化:"TypeError:moment.format不是函数".

import { Moment } from 'moment';
import { autoinject } from "aurelia-framework";

@autoinject
export class App {
  message: string;
  moment: Moment;

  constructor(moment: Moment) {
    this.message = moment.format();
  }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*agi 8

MomentJS是一个全局模块,仅导出moment变量.例如interface Moment,d.ts文件中的其他接口定义将不会导出为真实的.那些适用于TypeScript编译器和智能感知器.

这就是为什么你经历过上面的TS编译器和TypeError问题.您可能已经使用autoinject而不是浏览器欺骗了编译器.

时刻的定义文件:

declare module 'moment' {
    var moment: moment.MomentStatic;
    export = moment;
}
Run Code Online (Sandbox Code Playgroud)

为了使其正常工作,请使用如下导入语句:[moment docs]

import * as moment from 'moment';

之后,moment变量变为可用,您可以像平常一样使用它.

你班上的用法:

import * as moment from 'moment';

export class App {
    message = 'Hello World!';

    constructor(){
    }

    hello() : string {
        return moment().format();
    }
}
Run Code Online (Sandbox Code Playgroud)