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);
Our tsconfig.json has "esModuleInterop": true
.
import express from 'express';
That gives this error:
"node_modules/@types/express/index"' has no default export.ts
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.
NOTE: You must note that you can't use require and import at the same time in your node program and it is more preferred to use require instead of import as you are required to use the experimental module flag feature to run import program.
import-to-require packageSelect the line (or lines) with the 'import' ES6 syntax and press ctrl+alt+m to turn it into a line with 'require' ES5 syntax. You can select multiple lines to modify several import lines at a time. But doesn't support multi-cursors.
Use Import Instead of Require in Node App.
The major difference between require and import , is that require will automatically scan node_modules to find modules, but import , which comes from ES6, won't. Most people use babel to compile import and export , which makes import act the same as require .
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With