[英]Typescript resulting in cannot find module error
I am trying to build a basic Express api and am running in to an odd module not found
error.我正在尝试构建一个基本的 Express api,但遇到了一个奇怪的module not found
错误。 Before introducing TypeScript to my project, I never got this error.在将 TypeScript 引入我的项目之前,我从未遇到过这个错误。 This has been quite frustrating to resolve.解决这个问题非常令人沮丧。 I appreciate any suggestions on why I am getting this error and how to resolve.我很感激有关为什么我会收到此错误以及如何解决的任何建议。
server.ts服务器.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 api/api.ts
import express from "express";
const router = express.Router();
router.use('/', (req, res, next) => {
res.send('cool');
});
module.exports = router;
With typescript, we don't use module.exports but export directly like so:使用打字稿,我们不使用 module.exports 而是直接导出,如下所示:
import express from "express";
export const router = express.Router();
router.use('/', (req, res, next) => {
res.send('cool');
});
Then we can get the router with然后我们可以得到路由器
import {router} from './api'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.