Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
};
like image 482
NiaoBlush Avatar asked Jun 29 '18 10:06

NiaoBlush


People also ask

How do I enable IntelliSense in Visual Studio?

To access this options page, choose Tools > Options, and then choose Text Editor > C# > IntelliSense.

Why is IntelliSense not working in VS Code?

If the IntelliSense is installed and still not working then most of the time restarting/reloading the program will solve the issue. So give it a try. Step 1: To restart VS Code open VS Code and press Ctrl + Shift + P keys together to open the command palette and type Reload Window in the search.


1 Answers

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
}
like image 98
ippi Avatar answered Sep 20 '22 04:09

ippi