首页 > 解决方案 > 如何使用导入而不是要求创建快速应用程序

问题描述

这适用于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);

我们尝试过的

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

尝试#1

import express from 'express';

这给出了这个错误:

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

尝试#2

import * as express from 'express';
var app = express();

这给出了一个不同的错误:

无法调用其类型缺少调用签名的表达式。类型“typeof e”没有兼容的调用签名。ts(2349) index.ts(1, 1):类型源自此导入。命名空间样式的导入不能被调用或构造,并且会在运行时导致失败。请考虑在此处使用默认导入或导入要求。

标签: typescriptexpress

解决方案


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);

或者,您可以使用 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'. */
  }
}

并使用此默认导入导入:

import express from 'express' 
var app = express();

推荐阅读