Typescript - Importing Express not working
Asked Answered
R

4

18

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?

Reinertson answered 4/7, 2019 at 3:34 Comment(0)
S
24

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.

Sawhorse answered 4/7, 2019 at 7:38 Comment(0)
L
20

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.

https://github.com/microsoft/TypeScript-Node-Starter

Lurcher answered 4/7, 2019 at 4:11 Comment(4)
appreciate the answer, it's still giving me that same error when run server.tsReinertson
Hmmm make sure you're building your application with "tsc" and make sure your file extension is ".ts"Lurcher
gotcha, yeah i have a tsconfig.json file generated by tsc --init and also have a server.ts file that has that import statementReinertson
Hmmm.... its tough to say for sure what it is... the fact that it says the regular JS way is also an error makes me suspect it's like an invalid character somewhere in the file above the import or something "this is an unexpected identifier"Lurcher
F
0

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()
Freebooter answered 3/11, 2021 at 20:48 Comment(0)
N
0

this article helped me a bunch, primarily w/r to the module: "commonjs" package.json entry

Nitroso answered 7/10, 2022 at 14:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.