<reference>-ing a module

/// <reference>-ing a module

A common mistake is to try to use the /// <reference ... /> syntax to refer to a module file, rather than using an import statement. To understand the distinction, we first need to understand how compiler can locate the type information for a module based on the path of an import (e.g. the ... in import x from "...";, import x = require("...");, etc.) path.

The compiler will try to find a .ts, .tsx, and then a .d.ts with the appropriate path. If a specific file could not be found, then the compiler will look for an ambient module declaration. Recall that these need to be declared in a .d.ts file.

  • myModules.d.ts

    // In a .d.ts file or .ts file that is not a module:
    declare module "SomeModule" {
      export function fn(): string;
    }
    
  • myOtherModule.ts

    /// <reference path="myModules.d.ts" />
    import * as m from "SomeModule";
    

The reference tag here allows us to locate the declaration file that contains the declaration for the ambient module. This is how the node.d.ts file that several of the TypeScript samples use is consumed.

doc_TypeScript
2016-10-04 19:24:58
Comments
Leave a Comment

Please login to continue.