【问题标题】:Typescript resulting in cannot find module error打字稿导致找不到模块错误
【发布时间】:2020-03-01 17:06:36
【问题描述】:

我正在尝试构建一个基本的 Express api,但遇到了一个奇怪的 module not found 错误。在将 TypeScript 引入我的项目之前,我从未遇到此错误。解决这个问题非常令人沮丧。我感谢任何有关我为什么会收到此错误以及如何解决的建议。

server.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;

【问题讨论】:

    标签: javascript node.js typescript express


    【解决方案1】:

    使用 typescript,我们不使用 module.exports 而是直接导出,如下所示:

    import express from "express";
    
    export const router = express.Router();
    
    router.use('/', (req, res, next) => {
       res.send('cool');
    });
    

    然后我们就可以得到路由器了

    import {router} from './api'
    

    【讨论】:

      猜你喜欢
      • 2021-06-28
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      相关资源
      最近更新 更多