Table of Contents
Issue
This is what works with require
. We instead want it to use import
.
import { Request, Response, Application } from 'express';
// TODO Figure out how NOT to use require here.
const express = require('express');
var app: Application = express();
app.get('/', function (req: Request, res: Response) {
res.send('Hello World')
});
app.listen(3000);
What we have tried
Our tsconfig.json has "esModuleInterop": true
.
Attempt # 1
import express from 'express';
That gives this error:
“node_modules/@types/express/index”‘ has no default export.ts
Attempt # 2
import * as express from 'express';
var app = express();
That gives a different error:
Cannot invoke an expression whose type lacks a call signature. Type ‘typeof e’ has no compatible call signatures.ts(2349)
index.ts(1, 1): Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead.
Solution
TypeScript has special import syntax to deal with modules that export functions or some other custom objects as a whole (not as default export):
import { Request, Response, Application } from 'express';
import express = require('express');
var app: Application = express();
app.get('/', function (req: Request, res: Response) {
res.send('Hello World')
});
app.listen(3000);
Alternatively you can use TypeScript compiler options to alter imported module so that they have default export:
// tsconfig.json
{
"compilerOptions": {
"allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
}
}
and import using this default import:
import express from 'express'
var app = express();
Answered By – Kamil Szot
Answer Checked By – Cary Denson (BugsFixing Admin)