1

I'm trying to create a Node.js module with a single namespace using TypeScript. I need the classes of the module to be in separate files, and have references to each other. I also need this module to utilize other node modules. But if I understand right, TypeScript only supports namespaces if a namespace is contained within a single file or the namespace does not use external modules.

Some people present the use of post-build tools to make the final module work, which is nice but doesn't address all the errors TypeScript throws when combining cross-file namespaces and imports during development.

Is it true that the closest solution is to create a module per file, and create a web of inter-imports?

2

1 Answer 1

1

I find that what works best for me for module dependencies is to always use source references, e.g.:

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

Since you can't generate single-file output from tsc if you use language-level imports/modules, I have resorted to using require as a function and so on.

This seems to be the same solution chosen by the TypeScript developers themselves (search for "require(" there). As suggested by silentorb's comment, you can declare the require function as some variation of the following (or use DefinitelyTyped):

declare function require(name: string): any;

Note that there's often a lot of discussion on the whole modularity topic in TS over on the TS forums (one recent example).

Sign up to request clarification or add additional context in comments.

4 Comments

I wouldn't have understood your explanation by itself, but the first link pointed to demonstrated the solution. Avoid import foo = require('foo') Override require with declare var require: any;
Could you edit your answer to mention the code I have in my comment? I've seen this problem talked about several places without anyone presenting that code. The closest I saw was one sample where they overrode require, but I never understood why because their code didn't use it.
I put in the require declaration that I've used before, although yours is more versatile and the one in DefinitelyTyped is more detailed.
As an update, I recommend using ES6 modules in TypeScript these days.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.