Reputation: 10818
I have code like that in my app.ts
file:
app.use((req: Request, res: Response, next: Function) => {
//code
}
app.use(function(err: any, req: Request, res: Response, next: Function) {
// code
});
How can I move this functions to separate ts
file and then import them and use in my app.ts
?
app.use(Func1);
app.use(Func2);
What is the best way of doing that?
Upvotes: 1
Views: 1347
Reputation: 31924
You have two possibilities if you need to separate your code across multiple files:
Also called namespaces, these are akin to namespaces in other languages, although using it is slightly different from that in, say, C#.
namespace RequestHandlers {
export function Func1(req: Request, res: Response, next: Function) {
// code
}
export function Func2(err: any, req: Request, res: Response, next: Function) {
// code
}
}
Of course, you can separate a single namespace across multiple files, just how you'd do it in, say, C#. In that case you'd have two additional files, and in each of them your code would be surrounded by the namespace block.
Importing in Typescript is nothing more than aliasing in this case:
import Func1 = RequestHandlers.Func1;
import Func2 = RequestHandlers.Func2;
app.use(Func1);
app.use(Func2);
Of course, you can reference them directly as well, without using the import
statement. File ordering issues may arise, so make sure you use reference paths as well, using which the compiler will compile dependent files in order. A reference path indicates a file that should be compiled (and included in the output file) in advance.
External modules are what modules are called traditionally in Javascript. They are file based, each module a file. To use external modules, you need a module loading system, like RequireJS. The Node.js runtime environment comes with its own built-in module loading system.
Typescript will automatically consider a file with a top-level export or import statement as an external module:
requesthandlers.ts
export function Func1(req: Request, res: Response, next: Function) {
// code
}
export function Func2(err: any, req: Request, res: Response, next: Function) {
// code
}
Importing modules using the external-style import statement is supported in the Typescript compiler if a module loading syntax is selected for compilation (in Visual Studio, this can be found on the Project Settings -> TypeScript Build page), but will not work without a module loading system at runtime:
import * as RequestHandlers from "requesthandlers"; // by filename, without extension
app.use(RequestHandlers.Func1);
app.use(RequestHandlers.Func2);
The import ... from "..."
syntax is the ES6 module syntax, which is the preferred way to import in TypeScript.
Upvotes: 3
Reputation: 14847
a.ts:
export function Func1() {}
b.ts:
export function Func2() {}
app.ts:
import { Func1 } from './a';
import { Func2 } from './b';
app.use(Func1);
app.use(Func2);
Upvotes: -1