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?
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With