[英]Typescript resulting in cannot find module error
我正在嘗試構建一個基本的 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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.