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);
我们尝试过的
我们的 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):类型源自此导入。命名空间样式的导入不能被调用或构造,并且会在运行时导致失败。请考虑在此处使用默认导入或导入要求。
解决方案
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();
推荐阅读
- ruby-on-rails-5 - Rspec,Rails 5,Ransack:测试视图 index.html.erb
- list - 如何使用 Lisp 编写设置封面代码?(包括算法)
- julia - 选择结构数组或多个数组的指南
- python - 在表示从一个项目到另一个项目的相对距离的数据集上使用 K 均值聚类意味着什么?
- angular7 - 角料粘柱多于1列
- javascript - 在获取父元素的 id 时附加一个元素
- php - php通过自定义命令调用scrapy
- html - 找不到缺少的结束 div 标签
- mysql - 根据条件从表中检索结果
- django - Django,使用 sqlite 处理静态内容,使用 postgresql 处理其他所有内容