Typescript - Importing Express Not Working

Typescript - Importing Express Not Working

I have this in my app with the @types/express dependency installed

import express = require('express');

It is pointing to the express and saying this is an unexpected identifier when I run my server. I believe this is correct TS syntax and the regular JS way of const express = .. has the same error.

Do I need regular express? or wouldn't I need the one I already installed, which should be for TS specifically?

3 Answers

To replace require statement with import statement, for example:

    const express = require('express');

You can convert it to this:

    import * as express from "express";

And yes, you need both, regular express as dependency and @types/express as dev-dependency to have TypeScript type definitions working.

The syntax you want will be

import express from "express";

and it shouldn't result in a duplicate identifier error unless its simply a IDE bug. You can look into a common setup most people use to work with NodeJS/Typescript here.

4

I had a particularly difficult situation because I was using esmodules with our production/development, but commonjs with our testing tools.

I ended up getting it to work by using both imports.

app.ts

import express, * as express_test from "express"

const app = express ? express() : express_test()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.