【问题标题】:import modules as classes (dojo)将模块作为类导入 (dojo)
【发布时间】:2012-11-12 06:40:55
【问题描述】:

背景

目前在我工作的地方,我们使用 dojo.requires 来导入我们在每个类中使用的所有需要​​的类。然而,在 Dojo 2.0 中,他们正在摆脱 dojo.require 并转而采用 amd 要求风格(http://livedocs.dojotoolkit.org/releasenotes/migration-2.0):

require(["dijit/form/Button", "dojox/layout/ContentPane", ...], 
   function(Button, ContentPane, ...){
    // CODE HERE
});

我们目前在自己的 .d.ts 文件中定义了我们的 dojo/dijit 类,如下所示:

module dijit.form{
    export class Button extends dijit.form._FormWidget {
        showLabel : bool;
        _onClick (e:any) : any;
        _onButtonClick (e:any) : any;
        _setShowLabelAttr (val:any) : any;
        _clicked (e:any) : any;
        setLabel (content:String) : any;
        _setLabelAttr (content:String) : any;
        _setIconClassAttr (val:String) : any;
    }
}

这允许我们像下面这样扩展这些类:

class CustomButton extends dijit.form.Button {}

问题

我们希望能够让 typescript 生成 Dojo 2.0 (amd) 样式要求,并执行以下操作:

import Button = module("dijit/form/Button")
class CustomButton extends Button {}

我们曾希望编译成如下内容:

define(["require", "exports", "dijit/form/Button"], function(require, exports, Button)    
{
    ///....Generated class    
})

但是,这不起作用,因为 import 仅适用于模块而不适用于类。我们收到如下错误:

The name '"dijit/form/Button"' does not exist in the current scope
A module cannot be aliased to a non-module type

我们还尝试定义 dijit 类,例如:

declare module "dijit/form" {
    export class Button....
}

有没有一种方法可以实现我们正在尝试做的事情?

谢谢

【问题讨论】:

    标签: typescript


    【解决方案1】:

    在 AMD 模块中,模块等同于文件,因此如果您有一个名为:

    dijit.forms.ts 甚至 dijit.forms.d.ts

    你可以使用

    import forms = module("dijit.forms");
    
    var button = new forms.Button();
    

    在 AMD 应用程序的定义文件中,您不需要声明模块,因为文件就是模块。

    【讨论】:

    • 感谢您的回复,我们可以让它像那样工作,但问题是dojo的模块是类。使用你的例子,打字稿会生成像'define([“require”,“exports”,“dijit/form”],......'这样的定义,但我们需要它像'define([“require”,“出口”,“dijit/form/Button”]...'
    • 另一种选择是 declare var define: any; 并完全按照您的需要包含定义语句。你也可以包含一个更完整的定义声明。
    猜你喜欢
    • 2019-09-24
    • 2018-06-30
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多