何在TypeScript和SystemJS中使用Momentjs

何在TypeScript和SystemJS中使用Momentjs

本文介绍了如何在TypeScript和SystemJS中使用Momentjs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目的设置包括用于库的"jspm"工具和用于键入的"tsd"工具.

My project's setup includes 'jspm' tool for libraries and 'tsd' tool for typings.

在安装了矩的TypeScript d.ts文件(这些)之后,我找不到方法加载并实际使用矩实例.

After installing moment's TypeScript d.ts file (these), I can't find a way to load and actually use a moment instance.

/// <reference path="../../../typings/tsd.d.ts" />
import * as moment from "moment";
import * as _ from "lodash";
...
...
const now = (this.timestamp === 0) ? moment() : moment(this.timestamp);

我收到" TypeError:瞬间不是函数"

I get a "TypeError: moment is not a function"

定义的结构与 lodash 一样,效果很好,所以我不知道可能是什么原因.

The definitions are structured the same as lodash, which works fine, so I don't know what might be the cause.

任何人都可以帮忙吗?

推荐答案

我执行了以下操作:

我安装了moment 定义文件,如下所示:

I installed moment definition file as follows:

tsd install moment --save

然后我创建了 main.ts :

///<reference path="typings/moment/moment.d.ts" />

import moment = require("moment");
moment(new Date());

然后我跑了

$ tsc --module system --target es5 main.ts # no error
$ tsc --module commonjs --target es5 main.ts # no error

main.js看起来像这样:

// https://github.com/ModuleLoader/es6-module-loader/blob/v0.17.0/docs/system-register.md - this is the corresponding doc
///<reference path="typings/moment/moment.d.ts" />
System.register(["moment"], function(exports_1) {
    var moment;
    return {
        setters:[
            function (moment_1) {
                // You can place `debugger;` command to debug the issue
                // "PLACE XY"
                moment = moment_1;
            }],
        execute: function() {
            moment(new Date());
        }
    }
});

我的TypeScript版本是1.6.2.

My TypeScript version is 1.6.2.

这是我发现的:

Momentjs导出一个函数(即_moment = utils_hooks__hooksutils_hooks__hooks是一个功能,这很清楚.

Momentjs exports a function (i.e. _moment = utils_hooks__hooks and utils_hooks__hooks is a function, that's quite clear.

如果在我上面用PLACE XY表示的位置放置一个断点,则可以看到moment_1是一个对象(!),而不是一个函数.相关行: 1 2

If you place a breakpoint at the place I denoted as PLACE XY above, you can see that moment_1 is an object (!) and not a function. Relevant lines: 1, 2

总而言之,该问题与TypeScript无关.问题是systemjs不会保留momentjs导出函数的信息. Systemjs只是从模块中复制导出对象的属性(函数也是JavaScript中的对象).我想您应该在systemjs存储库中提出一个问题,以了解他们是否认为它是错误(或功能:)).

To conclude it, the problem has nothing to do with TypeScript. The issue is that systemjs does not preserve the information that momentjs exports a function. Systemjs simply copy properties of the exported object from a module (a function is an object in JavaScript too). I guess you should file an issue in systemjs repository to find out if they consider it to be a bug (or a feature :)).

这篇关于如何在TypeScript和SystemJS中使用Momentjs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 05:00