0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This works fine, if you put all your classes in one .ts file. But what would you do, when you want to import class1.ts and class2.ts into one dependency variable like "mymodule"?
You can't, regardless of whether or not you use export module mymodule {
1

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.