如何使用导入而不是要求创建快速应用程序

Sha*_*tin 4 express typescript

这是与require。相反,我们希望它使用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);
Run Code Online (Sandbox Code Playgroud)

我们尝试过的

我们的tsconfig.json具有"esModuleInterop": true

尝试#1

import express from 'express';
Run Code Online (Sandbox Code Playgroud)

这给出了这个错误:

“ node_modules / @ types / express / index”'没有默认的export.ts

尝试#2

import * as express from 'express';
var app = express();
Run Code Online (Sandbox Code Playgroud)

这给出了另一个错误:

无法调用类型缺少调用签名的表达式。类型'typeof e'没有兼容的呼叫签名。ts(2349)index.ts(1,1):类型起源于此导入。不能调用或构造名称空间样式的导入,并且将在运行时导致失败。考虑在此处使用默认导入或导入要求。

Kam*_*zot 5

TypeScript具有特殊的导入语法,以处理整体导出函数或某些其他自定义对象的模块(而不是默认导出):

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);
Run Code Online (Sandbox Code Playgroud)

另外,您可以使用TypeScript编译器选项来更改导入的模块,以便它们具有默认导出:

// 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'. */
  }
}
Run Code Online (Sandbox Code Playgroud)

并使用此默认导入进行导入:

import express from 'express' 
var app = express();
Run Code Online (Sandbox Code Playgroud)