使用Typescripts,在导入模块时,常常出一些难以理解的简单错误。下面就给出标准答案,让你在 import 模块的时候不再迷惑。
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);
另外一个简化方法,让你可以使用默认导出。首先在 tsconfig.json 中进行设置:
// 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();