javascript - 打字稿导致找不到模块错误
问题描述
我正在尝试构建一个基本的 Express api,但遇到了一个奇怪的module not found
错误。在将 TypeScript 引入我的项目之前,我从来没有遇到过这个错误。解决这个问题非常令人沮丧。我感谢任何有关我为什么会收到此错误以及如何解决的建议。
服务器.ts
import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
//import * as api from "api"; also tried this
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use('/api', require('./api'));
app.use('*', (req, res, next) => {
let error = new Error('404: not found');
next(error);
});
app.use((error, req, res, next) => {
res.status(500).send({
error: {
message: error.message
}
});
});
const port = 3000;
app.listen(port, () => {
console.log('listening on port', port);
});
module.exports = app;
api/api.ts
import express from "express";
const router = express.Router();
router.use('/', (req, res, next) => {
res.send('cool');
});
module.exports = router;
解决方案
使用打字稿,我们不使用 module.exports 而是直接导出,如下所示:
import express from "express";
export const router = express.Router();
router.use('/', (req, res, next) => {
res.send('cool');
});
然后我们可以得到路由器
import {router} from './api'
推荐阅读
- google-cloud-platform - Removing allUsers default acl on Google Cloud Storage (GCS)
- ubuntu-18.04 - Ubuntu 18.04 上的黄色显示
- regex - Search and replace with Notepad++ keeping after defined string
- laravel - 使用 API 调用登录 Laravel 用户以进行 Web 应用程序
- wordpress - 将搜索结果页面更改为自定义帖子类型的单页
- c# - 如何在鼠标单击 ogameobject 时禁用/启用 LineRenderer?
- java - How to calculate the sum of total items
- laravel-5.6 - Change the icon for incoming notification in Laravel
- c# - C# 数组如何处理内存?
- unix - 将文件名添加到计数数据