Search code examples
node.jstypescriptamdcommonjstypescript1.4

TypeScript won't resolve module when import is used


// Modules/MyModule.ts --------------------------------
import fs = require("fs");

module Hello {
    export function World(): string {
        return "Hello World";
    }
}


// Main/App.ts ----------------------------------------
console.log(Hello.World()); // Cannot find name 'Hello'

For some reason this produces the error specified above. The weird thing is if I uncomment the import statement I don't get this error anymore. (it's not used anyway)

Both produce the same error:

tsc Main/App.ts --module "commonjs"

tsc Main/App.ts --module "amd"

Is this really a compiler bug or am I missing something. Do I need to specify external module requires somehow different?


Solution

  • This one comes up quite a lot - the key to joy and happiness in TypeScript is to choose either internal modules or external modules and not both.

    I have written more extensively about choosing between internal and external modules in TypeScript. The bottom line is choose only one.

    In your case, you need to fully commit to external modules. Here is an updated example:

    // Modules/Hello.ts --------------------------------
    import fs = require("fs");
    
    export function World(): string {
        return "Hello World"
    }
    

    The module name for the above file is Hello, because it is in a file named Hello.ts.

    You can then use it like this...

    // Main/App.ts ----------------------------------------
    import Hello = require("./Modules/Hello");
    
    console.log(Hello.World());
    

    p.s. Node apps are compiled using commonjs mode - but this works for AMD too.