Skip to content
Advertisement

How to get intellisense for middleware of express in external file in vscode?

I’m trying to write a middleware of express. And I wrote that in a single file test2.js

In the server, I can have intellisense like:

enter image description here

In that single file, the middleware works fine, but I can’t have intellisense of req and res

Is there any way to get the intellisense?


Here is my server test1.js:

//test1.js
let http = require("http");
let express = require("express");
let app = express();

let middle = require("./test2.js");
app.use(middle);

app.use(function(req, res, next) {
  next();
});
http.createServer(app).listen(80);

Here is my middleware test2.js:

//test2.js
module.exports = function(req, res, next) {
  console.log("middle");
  next();
};

Advertisement

Answer

Maybe JSDoc is an option? You might need to install the type definitions: npm i @types/express -D (“Automatic Type Acquisition” in VS Code may or may not do that for your automatically)

/** @type {import("express").RequestHandler} */
module.exports = function (req, res, next) {
    req. // intellisense works
    next();
}

https://github.com/Microsoft/TypeScript/wiki/JSDoc-support-in-JavaScript


You can also use your own typescript declaration file:

myTypes.d.ts

import Express from "express";
declare global { 
    type RequestHandler = Express.RequestHandler;
}

Types are usually bound to the module’s scope, but you can import any type and re-declare it in the global scope.

Now vscode finds the types without the “dirty” {import("express")}

myMiddleware.js

/** @type RequestHandler */
module.exports = function (req, res, next) {
    req. // intellisense works
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement