简体   繁体   中英

Typescript - require AMD module like a namespace

To use Typescript with requireJs, I made two export classes in a common export module. This allows me to load them with requireJs like that:

require(["class1", "class2"], function (_class1, _class2) {
    var x = new _class1.mymodule.class1();
    var y = new _class2.mymodule.class2();
}

Here is an example of one of those class -files

export module mymodule {
    export class class1 {
        //some props and functions
    }
}

After long research, I didn't figured out how to reference just the module in a way like that:

// not working code ahead:
require(["class1", "class2"], function (mymodule) {
    var x = new mymodule.class1();
    var y = new mymodule.class2();
}

The last code block is plain javascript in a script HTML-tag.

Instead of writing

export module mymodule {
    export class class1 {
        //some props and functions
    }
}

Write this

export class class1 {
    //some props and functions
}

There's no need to wrap up your classes in a namespace with external modules, because the importer of them can decide which name they are referred to by. See also the " Needless Namespacing " section of the TypeScript documentation.

Ok, this is not what I imagined, but it works for me as a solution. Here is what I figured out:

  • Don't use export on internal dependencies like class1 , class2
  • If you need class2 inside class1 , just reference the typescript file with <reference path="class2" /> to get the declarations for TSLint
  • Create one wrapper typescript-file and references all dependencies like so:

wrapper.ts

/// <reference path="test/class1.ts" />
/// <amd-dependency path="class1" />
/// <reference path="test/class2.ts" />
/// <amd-dependency path="class2" />

export var class1: class1;
export var class2: class2;

javascript block

require(["wrapper"], function () {
    // do something with the dependencies
    var x = new class1();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM