user602271
user602271

Reputation:

Typescript: create external module from internal module

I currently have an internal module defined in foo.ts (edit: that can't be modified)

module Foo {
    export function foo(){
        console.log('foo');
    }
}

that I want to transform in an external module (to use in Node). So I created a bar.ts where I reference foo.ts and then I try to export it.

/// <reference path='foo.ts' />

export = Foo;

When I compile it using tsc -m commonjs --out bundle.js bar.ts I expect it to concatenate the declaration from foo.ts and then the export from bar.ts. However I get foo.ts and bar.ts compiled but separated and then bundle.js only has the same code as foo.js.

var Foo;
(function (Foo) {
    function foo() {
        console.log('foo');
    }
    Foo.foo = foo;
})(Foo || (Foo = {}));

Is this even possible to achieve?

Upvotes: 1

Views: 456

Answers (2)

user602271
user602271

Reputation:

It seems this can't be done using the export keyword of Typescript. The solution is (using the same foo.ts) use this bar.ts

/// <reference path="foo.ts" />

exports = Foo; // You will need node.d.ts

which gets compiled to a bundle of foo.ts and bar.ts. Bad news is that you lose the ability to (easily) create AMD and CommonJS modules with the same source (i.e. using export).

Upvotes: 0

basarat
basarat

Reputation: 276303

Replace:

module Foo {
    export function foo(){
        console.log('foo');
    }
}

With:

export function foo(){
    console.log('foo');
}

Root file level export or import statements identify a file as an external module.

Upvotes: 1

Related Questions