Express 4.x with Typescript - node.js

I am trying to make a express app with typescript.
This is my code so far:
//<reference path="./server/types/node.d.ts"/>
//<reference path="./server/types/express.d.ts"/>
import express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send('hi');
});
app.listen(3000);
nothing really shocking, I am just trying to make this work, but somehow, always when I try translate this file to a js file. I get strange errors, even if I change the express version to 3.1 (the express.d.ts is just supported for express 3.1 not for 4.x)
Any idea, where I can get a express.d.ts file for express 4.x or what I am doing wrong?
>> error TS2071: Unable to resolve external module ''express''
>> error TS2071: Module cannot be aliased to a non-module type.
>> error TS2095: Could not find symbol 'express'.

You reference comments are wrong. There needs to be three slashes /// :
///<reference path="./server/types/node.d.ts"/>
///<reference path="./server/types/express.d.ts"/>
The only way you can get that error if you are using this reference file https://github.com/borisyankov/DefinitelyTyped/blob/master/express/express.d.ts#L26 was that your reference comments were wrong and typescript was not reading that express.d.ts :)

Might I add that because you are using express 4.x and the type definitions are not up-to-date, you will be missing some key features that are central to express 4.x, such as Routers.
You have two choices at this point: update the type definitions, or use
var express = require('express');
instead, which removes some of the benefits that typescript provides, but is something you're bound to run into in the future with other node modules, such as mongoose.

Related

Remove warning on Node.js WebStorm

I am learning backend with Node.js and using middleware to catch for errors and send a different response code and body.
The warning is similar to err.message.
How do I remove these warnings?
Are you using express? Its methods are generated dynamically in runtime, so they can't be resolved during static code analysis. Installing TypeScript stubs should help to get methods work: put cursor on 'express' in const express = require('express'); , hit Alt+Enter and choose Install TypeScript definitions for better type information to install typings - see https://www.jetbrains.com/help/webstorm/configuring-javascript-libraries.html#ws_jsconfigure_libraries_ts_definition_files

Serving static files in Express (express.static vs app.static)

Through serving static files in Express .. I saw below code:
const express = require('express');
const app = express();
// Initialize the main project folder
app.use(express.static('website'));
Why we didn't use app.static() instead of express.static() as we already assigned express() to the app constant, and what is the difference between them?
Note: I tried to replace express with app and it said app.static is not a function. I also saw some NPM packages that use app.static() like wamjs for example, which is weird.
app.static() has nothing to do with Express.
Wam is a completely different framework (that may be Express-like in some ways, but it's not Express and not identical to Express). Here's a description on the NPM wam.js page:
Wam is a small koa and next.js inspired middleware framework for node.
If you want to program with Express, then use the Express documentation, not the Wam documentation and it will guide you to use app.use(somePath, express.static()). You can see in the Express doc for the app object, there is no mention of app.static(). That is apparently something that wasm.js invented for it's own framework.
Why we didn't use app.static() instead of express.static() as we already assigned express() to the app constant, and what is the difference between them?
Because Express doesn't have app.static(). It has express.static().
I also saw some NPM packages that use app.static() like wamjs for example, which is weird.
I wouldn't call it weird. wamjs is a different package with a different API. It is not Express so there should be no expectation that Express behaves like wamjs or that wamjs behaves like Express. They are different frameworks.

express.Router() and requires in Express.js

I am trying to organize my project according to Express 4.x new express.Router() method.
As Express' documentation describes it,
A router object is an isolated instance of middleware and routes. You
can think of it as a “mini-application,” capable only of performing
middleware and routing functions.
For the sake of better understanding, let's consider this project structure:
project/
index.js
routes/
myRouter.js
...
...
And the files themselves:
index.js
const express = require('express');
const app = express();
const path = require('path');
const myModule = require('myModule');
app.use('/myRouter', require('routes/myRouter'));
// some more code using myModule set of functions
routes/myRouter.js
const express = require('express');
const path = require('path');
const router = express.Router();
const myModule = require('myModule');
router.get('/', function(req, res){
// some more code using myModule set of functions
});
module.exports = router;
As you can see, both files need to use myModule's functions, so AFAIK both files need to require myModule.
How does Express handle this situation?
As I see it, Express directly imports myRouter's code into index.js via module.exports. If so, is the engine somehow pre-compiling it? And then aren't myRouters' requires redundant?
If not, how does it affect performance? Should I avoid routers for my kind of task?
First thing would be that it is not being compiled, it's not es6. Second app.js imports the module and run that module for your route so imports in your myRouter.js is completely necessary. This article would certainly help you understand modules. One more thing is that it does decrease your application performance. Express is used on node.js and node.js imports are optimised with V8 engine. So don't worry about performance.
How does Express handle this situation?
Express doesn't, Node does. From the docs
Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature....
So taking your application into consideration, myModule is already cached by the time the router loads it as app.js would be required first; any performance impact would be negligible.

Using Express() with TypeScript

I want to use the most recent version of Expess with node.js in TypeScript. The express.d.ts provided by microsoft in the samples seems to be built upon a versions prior to 3.0.x.
In previous version you could do
var app = express.createServer()
but after 3.0.x you should do:
var app = express();
Express.d.ts does not support this... I've found a hack around this:
I've added the following line to Express.d.ts:
export function(): any;
In app.ts when I want to create the app object I do the following:
var app = <express.ExpressServer>express();
This seems to fix the issue, it's compiling without an error, and also I get intellisense support. However this is a hack... First of all why can't I write something like this?
export function(): ExpressServer;
Is this the recommended way to fix this issue?
Pretty old discussion, but I ran into the same problem recently and found that there is a new express.d.ts that properly supports express 3 on the DefinitelyTyped site.
You should be able to add this ambient function declaration to express.d.ts to get what you want.
declare function express(): ExpressServer;
if you declare express this way: import * as express from "express", you will get this error in runtime, declaring it this way: const express = require "express", won't throw any error.
Also, don't forget to declare app variable or property type as express.Application
Here's a sample project - Express 4.x app in TypeScript: https://github.com/czechboy0/Express-4x-Typescript-Sample

node.js express.js object is not a function call_non_function

I have this error:
TypeError: object is not a function
at Object.CALL_NON_FUNCTION (native)
For this line:
var app=express();
I tryed to install express/connect again, but.. nothing.
Thanks!
EDIT
I'm express 2.5.8.
my code:
error:
var http=require('http');
var app=express();
var server=http.createServer(app);
(i forget why i need to use this code, i think for cookie handshake works.
I have resole the probleme (hanskake cookie) editing manager.js, so i dont need to use this code. But can be interesting to understand why no works (and why i wanted to use)).
no error:
var app=express.createServer();
You have the wrong express version. You can only create the server with express() in v3.x.x. Before this version, express can not be called as a Function. Try either changing your code to create the app the old way or try updating express.

Resources