Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference External Modules in TypeScript

I have an application which I want to convert step by step to TypeScript. Currently we are using browserify to generate a bundle.

When converting to TypeScript I am having some modules which have not yet been converted. In the TypeScript Handbook it says that I can reference external modules, when specifying a type definition file for it.

I have a module A.js which is not yet converted to TypeScript. I have a global type definition file which defines

declare module "A" {
    export function foo();
    export function bar();
}

I am importing my module like this:

///<reference path="../../typings/NotYetConvertedModules.d.ts" />
import A = require('../someFolder/A');

when compiling this I get

error TS2307: Cannot find external module '../someFolder/A'

When requiring it with require('A') the compilation step works but the module loader cannot find the file, since I am not having a global alias for it.

Is there any way to solve this?

like image 259
david Avatar asked Dec 25 '22 23:12

david


2 Answers

When you declare a module name in quotes, the quoted name becomes the alias. So when you write...

declare module 'A' { //...

You import it using the following (no matter where you are importing it):

import a = require('A');

This is useful when creating definitions for node.js modules, for example.

You cannot use a string alias with a relative path, so you can't have:

declare module '../SomeFolder/A' { //...

But you can place a definition file named a.d.ts in the appropriate location (SomeFolder).

The file ./SomeFolder/a.d.ts looks like this:

declare module A {
    export function foo();
    export function bar();
}

export = A;

The file ./Scripts/AnotherFolder/example.ts looks like this:

import A = require('../../SomeFolder/A'); 

You will need to adjust the path based on your exact folder structure, but you can see the idea. Importantly, you don't need the reference comment when importing the module from the same folder as the definition file.

like image 176
Fenton Avatar answered Dec 28 '22 15:12

Fenton


Assuming you are using external modules (which means that the module ID depends on the file name)

Instead of writing in ../../typings/NotYetConvertedModules.d.ts

declare module "A" {
    export function foo();
    export function bar();
}

you should rather simply write in ../someFolder/A.d.ts

export function foo();
export function bar();
like image 24
Benjamin Avatar answered Dec 28 '22 15:12

Benjamin